DOM (Document Object Model) – Complete Notes
What is the DOM?
The DOM is a programming interface for HTML and XML documents.
It represents the page structure as a tree of objects (called nodes).
• Each element, attribute, and text is a node.
• The DOM allows JavaScript to interact with and modify HTML and CSS.
DOM Structure
Example HTML:
html
CopyEdit
<html>
<head>
<title>Page</title>
</head>
<body>
<h1>Hello</h1>
</body>
</html>
DOM Tree:
css
CopyEdit
Document
└── html
├── head
│ └── title
└── body
└── h1
Types of Nodes
Node Type Description
document Entry point of the DOM
element HTML tags like <p>, <div>
text Text inside elements
attribute HTML attributes like class
comment Comments in the HTML
Accessing the DOM in JavaScript
1. document Object
The root of every HTML page's DOM.
js
CopyEdit
console.log(document.title); // Get title
console.log(document.body); // Get <body> element
2. Selecting Elements
Method Description
getElementById(id) Select by ID
getElementsByClassName(name) Select by class name (HTMLCollection)
getElementsByTagName(name) Select by tag (HTMLCollection)
querySelector(selector) First match (CSS selector)
querySelectorAll(selector) All matches (NodeList)
js
CopyEdit
document.getElementById("header");
document.querySelector(".box");
DOM Traversal
Parent & Children
js
CopyEdit
element.parentNode
element.children
element.firstChild
element.lastChild
Siblings
js
CopyEdit
element.nextSibling
element.previousSibling
Manipulating the DOM
1. Change Content
js
CopyEdit
element.textContent = "Hello!";
element.innerHTML = "<b>Bold</b>";
2. Change Attributes
js
CopyEdit
element.setAttribute("class", "newClass");
element.getAttribute("id");
element.removeAttribute("href");
3. Change Styles
js
CopyEdit
element.style.color = "blue";
element.style.backgroundColor = "yellow";
4. Create & Append Elements
js
CopyEdit
let newDiv = document.createElement("div");
newDiv.textContent = "I'm new!";
document.body.appendChild(newDiv);
5. Remove Elements
js
CopyEdit
element.remove();
DOM Events
Adding Event Listeners
js
CopyEdit
element.addEventListener("click", () => {
alert("Clicked!");
});
Event Type Description
click Mouse click
mouseover Mouse enters element
Event Type Description
keydown Keyboard key press
submit Form submission
change Input field changed
DOM vs Virtual DOM (React)
Feature DOM Virtual DOM (React)
Real structure Actual browser DOM tree JS object representation
Speed Slower, full re-render Faster, only diffs are re-rendered
Manipulation Manual via JS Declarative via state/props
Summary
• DOM is a tree-like structure of a webpage.
• JavaScript can select, modify, and delete elements using DOM APIs.
• DOM is event-driven, allowing for dynamic interaction.
• Mastery of DOM is essential for frontend development and frameworks like React,
Vue, etc.