DOM stands for Document Object Model. It’s a tree-like structure that represents the contents of an HTML document.
When a webpage loads, the browser turns your HTML into a DOM tree, where:
📌 In short: JavaScript uses the DOM to interact with your web page dynamically.
<html>
<body>
<h1>Hello</h1>
<p>This is a paragraph.</p>
</body>
</html>Document
└── html
└── body
├── h1
└── p| Method | Description |
|---|---|
getElementById() | Finds element by ID |
getElementsByClassName() | Finds elements by class name |
getElementsByTagName() | Finds elements by tag |
querySelector() | Finds first matching element (CSS) |
querySelectorAll() | Finds all matching elements (CSS) |
<p id="demo" class="text">Hello!</p>document.getElementById("demo"); // By ID
document.getElementsByClassName("text"); // By class
document.querySelector("p"); // First <p>
document.querySelectorAll("p"); // All <p>Replaces the HTML content inside an element.
document.getElementById("demo").innerHTML = "Updated!";Changes only the text (ignores HTML tags).
document.getElementById("demo").textContent = "Plain Text";const box = document.getElementById("box");
box.style.backgroundColor = "blue";
box.style.fontSize = "20px";const newP = document.createElement("p");
newP.textContent = "This is a new paragraph.";
document.body.appendChild(newP);const item = document.getElementById("removeMe");
item.remove();Or using parent element:
item.parentNode.removeChild(item);You can combine DOM selection with events:
document.getElementById("btn").addEventListener("click", function () {
document.getElementById("demo").textContent = "Button clicked!";
});| Property | Description |
|---|---|
parentNode | Access parent element |
children | Access all child elements |
firstElementChild | First child element |
lastElementChild | Last child element |
nextElementSibling | Next element at the same level |
previousElementSibling | Previous element at same level |
const list = document.getElementById("myList");
console.log(list.children); // HTMLCollection of li elementsconst link = document.getElementById("myLink");
console.log(link.getAttribute("href")); // Get
link.setAttribute("href", "https://example.com"); // Setconst box = document.querySelector(".box");
box.classList.add("active"); // Add class
box.classList.remove("box"); // Remove class
box.classList.toggle("hidden"); // Toggle classinnerHTML.<li> item and add it to an unordered list.setTimeout().src attribute of an image dynamically.