12. Document Object Model (DOM) in JavaScript – Complete Guide

  1. What is DOM ?

    » The Document Object Model (DOM) is a programming interface that represents the structure of an HTML or XML document as a tree-like hierarchy.

    » The DOM allows JavaScript to interact with and modify web pages dynamically.

  2. How does the DOM works ?

    When a web page is loaded, the browser parses the HTML and creates a tree-like structure called the DOM. This structure consists of:

    • Nodes (Everything in the document is a node)

    • Elements (HTML tags like <div>, <p>, <h1>, etc.)

    • Attributes (Like class, id, src, etc.)

    • Text Nodes (The text inside elements)

  1. Types of Nodes in the DOM ?

There are different types of nodes in the DOM tree:

  1. Element Node – Represents HTML elements (e.g., <p>, <div>).

  2. Text Node – Represents text inside an element.

  3. Attribute Node – Represents attributes of an element.

  4. Comment Node – Represents comments inside the HTML.

Example of DOM Structure

<!DOCTYPE html>
<html>
<head>
    <title>DOM Example</title>
</head>
<body>
    <h1 id="heading">Hello, DOM!</h1>
    <p class="para">Welcome to the Document Object Model.</p>
</body>
</html>

Corresponding DOM Tree

DOCUMENT  
 ├── HTML  
 │   ├── HEAD  
 │   │   ├── TITLE (Element Node)  
 │   │   │   ├── "DOM Example" (Text Node)  
 │   ├── BODY  
 │       ├── H1 (Element Node)  
 │       │   ├── "Hello, DOM!" (Text Node)  
 │       ├── P (Element Node)  
 │           ├── "Welcome to the Document Object Model." (Text Node)
  1. Access the DOM elements

    1. Using document.getElementById()

let heading = document.getElementById("heading"); // select element which have id heading
console.log(heading.innerText); // Output in browser console: Hello, DOM!
  1. Using document.getElementsByClassName()

     let paragraphs = document.getElementsByClassName("para");
     console.log(paragraphs[0].innerText); // Output: Welcome to the Document Object Model.
    
  2. Using document.getElementsByTagName()

     let allParas = document.getElementsByTagName("p");
     console.log(allParas.length); // Output: Number of <p> elements
    
  3. Using document.querySelector()

     let firstPara = document.querySelector(".parabyclass"); // . for classname , #for id 
     console.log(firstPara.innerText); // Output: Welcome to the Document Object Model.
    
  4. Using document.querySelectorAll()

     let allParas = document.querySelectorAll(".para");
     allParas.forEach(para => console.log(para.innerText));
    
  5. Modifying DOM Elements

    JavaScript allows us to change element properties and content dynamically.

    1. Changing Text Content:

document.getElementById("heading").innerText = "Modified Heading!"; 
document.getElementById("heading").textContent = "Another Change!";
document.getElementById("heading").innerHTML = "<i>Italic Text</i>";
  1. Changing Attributes :

     let img = document.getElementById("myImage");
     img.src = "newImage.png";
     img.alt = "New Image";
    
  2. Changing CSS Styles :

     document.getElementById("heading").style.color = "red";
     document.getElementById("heading").style.fontSize = "24px";
    
  3. Creating and Removing Element

    1. Creating Elements

       let newPara = document.createElement("p");
       newPara.innerText = "This is a new paragraph.";
       document.body.appendChild(newPara);
      
  1. Removing Element:

     let removePara = document.getElementById("heading");
     removePara.remove();
    
  2. Replacing Elements

     let newHeading = document.createElement("h2");
     newHeading.innerText = "New Heading!";
     let oldHeading = document.getElementById("heading");
     document.body.replaceChild(newHeading, oldHeading);
    
  3. Event Handling in the DOM

    1. Inline handling:

<button onclick="sayHello()">Click Me</button>

<script>
function sayHello() {
    alert("Hello, DOM!");
}
</script>
  1. Using addEventListener()

     document.getElementById("heading").addEventListener("click", function() {
         alert("Heading Clicked!");
     });
    
  2. Traversing the DOM

let parent = document.getElementById("heading").parentNode; // Get Parent Node
console.log(parent) // it will print that parent element , e.g <div> hii </div>
let children = document.getElementById("heading").childNodes; // Get Child Nodes
let firstChild = document.getElementById("heading").firstChild; // First Child
let nextSibling = document.getElementById("heading").nextSibling; // Next Sibling

Event Object in Javascript

» In JavaScript, the Event Object is a built-in object that contains details about an event that occurs in the browser, such as a click, key press, or form submission.

» It is automatically passed to event handler functions when an event occurs.

  1. Accessing the Event Object

     document.addEventListener("click", function(event) {
         console.log(event); // Logs the event object
     });
    

2. Common Properties of the Event Object

typeType of event (e.g., "click", "keydown")
targetThe element that triggered the event
clientX, clientYX and Y coordinates of the mouse event relative to the viewport
pageX, pageYX and Y coordinates of the mouse event relative to the document
key, codeThe key pressed (for keyboard events)
altKey, ctrlKey, shiftKeyBoolean values indicating if modifier keys were pressed
preventDefault()Prevents the default action of the event (e.g., stopping a link from navigating)
stopPropagation()Stops the event from bubbling up or capturing down the DOM
  1. Examples: Click events

     document.getElementById("myButton").addEventListener("click", function(event) {
         console.log("Event Type: ", event.type);  //Event Type : click
         console.log("Clicked Element:", event.target); //Clicked Element: <button id=​"myButton">​ Hello ​</button>​
         console.log("Mouse Position:", event.clientX, event.clientY);//Mouse Position: 27 92
     });
    

Interview Questions

  1. What is the difference between innerHTML, innerText, and textContent?

    • innerHTML → Returns/sets the HTML content inside an element.

    • innerText → Returns/sets only the visible text, excluding hidden elements.

    • textContent → Returns/sets all text, including hidden elements.

  2. What are NodeLists and HTMLCollections?

    • NodeList is a static or live list of elements returned by querySelectorAll().

    • HTMLCollection is a live collection of elements returned by getElementsByClassName() or getElementsByTagName().

  3. What is the difference between appendChild() and innerHTML?

    • appendChild() adds an element without replacing the existing content.

    • innerHTML replaces existing content and can execute embedded scripts.

  4. What will be the output ?

     document.body.innerHTML = "<h1>Hello</h1>";
     console.log(document.body.firstChild.nodeName);
    

    Output: "H1" (First child is the <h1> element)

  5. When you click ctrl + s in browser a pop up will appear ,How to stop this event ?

     document.addEventListener("keydown", function(event) {
         console.log("Key Pressed:", event.key);
         console.log("Key Code:", event.code);
         if (event.ctrlKey && event.key === "s") {
             event.preventDefault(); // Prevent browser save action
             console.log("Save disabled!");
         }
     });
    

Next Topic

map-filter-reduce