12. Document Object Model (DOM) in JavaScript – Complete Guide
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.
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)
Types of Nodes in the DOM ?
There are different types of nodes in the DOM tree:
Element Node – Represents HTML elements (e.g.,
<p>
,<div>
).Text Node – Represents text inside an element.
Attribute Node – Represents attributes of an element.
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)
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!
Using
document.getElementsByClassName()
let paragraphs = document.getElementsByClassName("para"); console.log(paragraphs[0].innerText); // Output: Welcome to the Document Object Model.
Using
document.getElementsByTagName()
let allParas = document.getElementsByTagName("p"); console.log(allParas.length); // Output: Number of <p> elements
Using
document.querySelector()
let firstPara = document.querySelector(".parabyclass"); // . for classname , #for id console.log(firstPara.innerText); // Output: Welcome to the Document Object Model.
Using
document.querySelectorAll()
let allParas = document.querySelectorAll(".para"); allParas.forEach(para => console.log(para.innerText));
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>";
Changing Attributes :
let img = document.getElementById("myImage"); img.src = "newImage.png"; img.alt = "New Image";
Changing CSS Styles :
document.getElementById("heading").style.color = "red"; document.getElementById("heading").style.fontSize = "24px";
Creating and Removing Element
Creating Elements
let newPara = document.createElement("p"); newPara.innerText = "This is a new paragraph."; document.body.appendChild(newPara);
Removing Element:
let removePara = document.getElementById("heading"); removePara.remove();
Replacing Elements
let newHeading = document.createElement("h2"); newHeading.innerText = "New Heading!"; let oldHeading = document.getElementById("heading"); document.body.replaceChild(newHeading, oldHeading);
Event Handling in the DOM
1. Inline handling:
<button onclick="sayHello()">Click Me</button>
<script>
function sayHello() {
alert("Hello, DOM!");
}
</script>
Using
addEventListener()
document.getElementById("heading").addEventListener("click", function() { alert("Heading Clicked!"); });
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.
Accessing the Event Object
document.addEventListener("click", function(event) { console.log(event); // Logs the event object });
2. Common Properties of the Event Object
type | Type of event (e.g., "click" , "keydown" ) |
target | The element that triggered the event |
clientX , clientY | X and Y coordinates of the mouse event relative to the viewport |
pageX , pageY | X and Y coordinates of the mouse event relative to the document |
key , code | The key pressed (for keyboard events) |
altKey , ctrlKey , shiftKey | Boolean 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 |
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
What is the difference between
innerHTML
,innerText
, andtextContent
?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.
What are NodeLists and HTMLCollections?
NodeList
is a static or live list of elements returned byquerySelectorAll()
.HTMLCollection
is a live collection of elements returned bygetElementsByClassName()
orgetElementsByTagName()
.
What is the difference between
appendChild()
andinnerHTML
?appendChild()
adds an element without replacing the existing content.innerHTML
replaces existing content and can execute embedded scripts.
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)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!"); } });