🌐 What is the DOM?
DOM stands for Document Object Model. It’s a tree-like structure that represents every element on a web page—text, images, buttons, and more. When a browser loads an HTML document, it converts it into the DOM so JavaScript can read, modify, and interact with it.
Think of the DOM as a live map of your webpage that JavaScript can manipulate.
🧠 Why Does JavaScript Need the DOM?
Without the DOM, JavaScript would have no way to:
-
Add or remove HTML elements
-
Change text or image content
-
Handle user inputs and events
-
Update the page dynamically without reloading
The DOM provides JavaScript with an API (Application Programming Interface) to access and modify the structure, style, and content of web pages.
📊 How the DOM is Structured
Here’s a visual example of a simple HTML document and how it’s represented in the DOM:
<html>
<head><title>My Page</title></head>
<body>
<h1>Hello World</h1>
<button>Click me</button>
</body>
</html>
The DOM tree would look like:
Document
└── html
├── head
│ └── title
└── body
├── h1
└── button
JavaScript can traverse this structure, select elements, and manipulate them.
🧩 Selecting Elements from the DOM
Before you manipulate anything, you must select the element. JavaScript provides several methods:
🔍 Common DOM Selectors:
// By ID
document.getElementById("myId");
// By class
document.getElementsByClassName("myClass");
// By tag
document.getElementsByTagName("div");
// Modern & powerful: CSS selectors
document.querySelector("div.container");
document.querySelectorAll("ul li");
✅ Best Practice: Use querySelector() and querySelectorAll() for cleaner, CSS-like selection.
✏️ Modifying DOM Elements
Once you’ve selected elements, you can modify their content, style, or attributes.
📝 Change Text or HTML
document.getElementById("heading").innerText = "Updated Title";
document.querySelector("div").innerHTML = "<strong>Bold text</strong>";
🎨 Change CSS Style
document.querySelector("p").style.color = "blue";
document.querySelector("p").style.fontSize = "20px";
⚙️ Change Attributes
document.querySelector("img").src = "new-image.jpg";
document.querySelector("a").setAttribute("href", "https://example.com");
➕ Creating & Removing Elements
➕ Add New Elements
let newDiv = document.createElement("div");
newDiv.innerText = "This is a new div!";
document.body.appendChild(newDiv);
Join the conversation! Your thoughts help the community grow.