What is the DOM

🌐 What is the DOM?

  • The DOM is a programming interface for web documents.
  • It represents the HTML or XML document as a tree structure.
  • Each element (like <div>, <p>, <h1>, etc.) becomes a node in this tree.

Example:

<html>
  <body>
    <h1>Hello</h1>
    <p>World</p>
  </body>
</html>

DOM Tree Representation:

Document
 └── html
      └── body
           ├── h1 → "Hello"
           └── p → "World"

🛠️ DOM in JavaScript

JavaScript can access and manipulate the DOM to change the structure, style, and content of a webpage dynamically.

1. Accessing Elements

document.getElementById("myId");        // by id
document.getElementsByClassName("cls"); // by class
document.getElementsByTagName("p");     // by tag
document.querySelector("#myId");        // first match
document.querySelectorAll(".cls");      // all matches

2. Changing Content

document.getElementById("demo").innerHTML = "Hello World!";
document.querySelector("p").textContent = "Updated text";

3. Changing Styles

document.getElementById("demo").style.color = "red";
document.querySelector("h1").style.backgroundColor = "yellow";

4. Creating & Appending Elements

let newDiv = document.createElement("div");
newDiv.textContent = "I am new here!";
document.body.appendChild(newDiv);

5. Removing Elements

let element = document.getElementById("demo");
element.remove();

6. Event Handling

document.getElementById("btn").addEventListener("click", function() {
  alert("Button clicked!");
});

🎯 Why DOM is Important?

  • It allows dynamic changes without reloading the page.
  • Used in interactive web apps (like forms, games, single-page apps).
  • Basis of frameworks like React, Vue, Angular (they manage the DOM efficiently).

Leave a Reply