Dom Api
What is DOM API
The DOM API (Document Object Model API) is a core part of web development — it allows JavaScript to interact with, modify, and manipulate the structure and content of web pages dynamically.
What is DOM
The Document Object Model (DOM) is a tree-like representation of an HTML or XML document.
When a web page is loaded, the browser creates a DOM — a structured model of the document where every element (like <p>, <div>, <img>, etc.) is a node in this tree.
Example HTML:
<html>
<body>
<h1>Hello World</h1>
<p>This is a paragraph.</p>
</body>
</html>
DOM representation (simplified):
Document
└── html
└── body
├── h1
└── p
Accessing Elements
You can use the DOM API to select elements from the document.
| Method | Description |
| document.getElementById("id") | Selects an element by its id |
| document.getElementsByClassName("class") | Selects elements by class name (returns HTMLCollection) |
| document.getElementsByTagName("tag") | Selects elements by tag name |
| document.querySelector("selector") | Selects the first element matching a CSS selector |
| document.querySelectorAll("selector") | Selects all elements matching a CSS selector (returns NodeList) |
Modifying Elements
You can dynamically update a page without reloading it.
change content:
heading.textContent = "Welcome to my site!";
change html:
heading.innerHTML = "<em>Welcome!</em>";
change attributes:
document.querySelector("img").src = "new-image.jpg";
change styles:
heading.style.color = "blue";
heading.style.fontSize = "24px";
Creating & Removing Elements
The DOM API lets you create, append, and delete elements.
create:
const newDiv = document.createElement("div");
newDiv.textContent = "I am new here!";
append:
const container = document.getElementById('container');
const p = document.createElement('p');
p.textContent = 'Hello world!';
const span = document.createElement('span');
span.textContent = ' Hello again';
// Add both elements at once
container.append(p, span, ' Nice to meet you!');
document.body.appendChild(newDiv);
remove:
document.body.removeChild(newDiv);
Traversing the DOM
The DOM tree can be navigated using parent, child, and sibling relationships.
| Method | Description |
element.parentNode | Access the parent element |
element.children | Get all child elements |
element.firstChild | Get first child node |
element.lastChild | Get last child node |
element.nextSibling | Get siblings |
element.previousSibling | Get siblings |
Event Handling
DOM API enables event-driven programming — responding to user actions like clicks, inputs, etc.
Add Event Listener:
button.addEventListener("click", () => {
alert("Button clicked!");
});
AI-generated Content Disclaimer
Some portions of this text were created with the assistance of AI language models. While effort has been made to ensure accuracy, the content may contain errors or incomplete information. Please use your own judgment and verify details when necessary.
