The DOM Document Object Model allows JavaScript to interact with HTML elements.
Without the DOM, JavaScript cannot:
Change webpage content, Respond to button clicks, Validate forms, Create interactive websites
This is one of the most important topics for frontend development.
๐ง 1. What is the DOM?
DOM stands for Document Object Model.
It represents an HTML page as a tree of objects, allowing JavaScript to access and modify elements.
Example HTML
<!DOCTYPE html>
<html>
<body>
<h1 id="title">Hello World</h1>
</body>
</html>
JavaScript can access this element using its ID.
const heading = document.getElementById("title");
console.log(heading);๐ณ 2. DOM Tree Structure
Every HTML page is organized like a tree.
Document
โ
โโโ html
โ
โโโ head
โ
โโโ body
โ
โโโ h1
โโโ p
โโโ button
JavaScript can navigate this tree to access or modify elements.
๐ 3. Selecting Elements
By ID
const title = document.getElementById("title");By Class
const boxes = document.getElementsByClassName("box");By Tag Name
const paragraphs = document.getElementsByTagName("p");Using querySelector()
Returns the first matching element.
const button = document.querySelector(".btn");Using querySelectorAll()
Returns all matching elements.
const buttons = document.querySelectorAll(".btn");โ๏ธ 4. Changing Content
Using textContent
const heading = document.getElementById("title");
heading.textContent = "Welcome";Using innerHTML
heading.innerHTML = "<span>Hello JavaScript</span>";
Difference
textContent: Plain text
innerHTML: Supports HTML
๐จ 5. Changing Styles
const heading = document.getElementById("title");
heading.style.color = "blue";
heading.style.fontSize = "40px";๐ท๏ธ 6. Working with CSS Classes
Add Class
element.classList.add("active");Remove Class
element.classList.remove("active");Toggle Class
element.classList.toggle("dark");โ 7. Creating New Elements
const para = document.createElement("p");
para.textContent = "This is a new paragraph.";๐ 8. Adding Elements to the Page
document.body.appendChild(para);
โ 9. Removing Elements
const box = document.getElementById("box");
box.remove();๐ 10. Replacing Elements
const newHeading = document.createElement("h2");
newHeading.textContent = "New Heading";
heading.replaceWith(newHeading);๐ฑ๏ธ 11. Event Listeners
Events make webpages interactive.
Click Event
const button = document.querySelector("button");
button.addEventListener("click", () => {
console.log("Button clicked");
});Double Click
button.addEventListener("dblclick", () => {
console.log("Double Clicked");
});โจ๏ธ 12. Keyboard Events