1. What Is the DOM?
The Document Object Model (DOM) is an in-memory, tree-structured API created by the browser. It represents the HTML document as a hierarchy of live JavaScript objects that programs can read, traverse, and modify dynamically.
2. How HTML Becomes the DOM
HTML Bytes
Raw HTML arrives over the HTTP network stream.
Tokenizer
Parsed into start tags, end tags, and attribute tokens.
DOM Tree
Linked into nested object nodes (Document ➔ Body ➔ Divs).
Render Tree
Combined with CSSOM and painted on the screen.
3. Understanding the DOM Tree
└── html
├── head (title, meta, link)
└── body
├── header (h1, nav)
├── main (section, p, button)
└── footer
4. Nodes vs Elements
Everything in the DOM is a Node (including element tags, plain text, comments, and document itself). An Element is specifically a Node that represents an HTML tag (like <div> or <p>).
5. Selecting Elements with Modern Selectors
const title = document.getElementById("main-title");
// Select first match using any CSS selector
const heroBtn = document.querySelector(".hero-banner .btn-primary");
// Select ALL matches into a static NodeList
const cards = document.querySelectorAll(".product-card");
cards.forEach(card => console.log(card));
6. Changing Content: textContent vs innerHTML
element.textContent
Sets or gets raw plain text. Prevents XSS vulnerabilities because HTML tags are not parsed.
element.innerHTML
Parses string as raw HTML. Never pass unsanitized user input into innerHTML!
7. Dynamic Styles & classList
// Best Practice: Toggle CSS classes instead of inline styles
card.classList.add("dark-theme");
card.classList.remove("hidden");
card.classList.toggle("active");
// Checking if a class exists
if (card.classList.contains("active")) {
console.log("Card is currently active!");
}
8. Changing Attributes
link.setAttribute("href", "https://pathubs.com");
link.setAttribute("target", "_blank");
console.log(link.getAttribute("href")); // "https://pathubs.com"
link.removeAttribute("target");
9. Creating and Removing Elements
const newBadge = document.createElement("span");
newBadge.textContent = "PRO";
newBadge.classList.add("badge");
// 2. Append to parent container
document.querySelector(".user-card").append(newBadge);
// 3. Removing an element
newBadge.remove();
10. Traversing the DOM Hierarchy
const parentList = item.parentElement; // <ul>
const nextSibling = item.nextElementSibling; // Next <li>
const prevSibling = item.previousElementSibling; // Prev <li>
const allChildren = parentList.children; // HTMLCollection of all <li>s
11. DOM Events & addEventListener
submitBtn.addEventListener("click", (event) => {
event.preventDefault();
console.log("Button clicked! Target:", event.target);
});
12. Event Object, Target & Bubbling
When an event triggers on a button inside a card, the event fires on the button first, then bubbles up to the card, then to <body>, then to document. This allows powerful Event Delegation where one listener on the parent handles clicks for all current and future child elements.
13. Building Dynamic Web Pages: Real World Flow
form.addEventListener("submit", (e) => {
e.preventDefault();
const text = input.value.trim();
if (!text) return;
const li = document.createElement("li");
li.textContent = text;
taskList.append(li);
input.value = "";
});
14. Common DOM Beginner Mistakes
- Selecting elements before DOM is loaded: Always load scripts with
defer. - Using innerHTML for user inputs: Leads to dangerous XSS vulnerabilities. Use
textContent. - Modifying style properties one-by-one: Use
classList.toggle()with pre-styled CSS classes instead of repetitive inline style calls.
15. DOM Clean Code Best Practices
- Cache DOM queries in constants: Don't query the same selector 50 times in a loop.
- Use Event Delegation: Attach 1 listener to the parent list instead of 100 listeners to each list item.
- Batch DOM insertions: Use
document.createDocumentFragment()when appending multiple nodes.