Chapter 33: DOM Introduction
Introduction to the DOM (Document Object Model), written as if I am your patient teacher sitting next to you — explaining everything slowly, clearly, with many small examples, real-life analogies, visual drawings (in text), common beginner mistakes, and practical JavaScript code you can copy-paste and try immediately.
We will go step-by-step so you really feel what the DOM is, why it exists, and how people actually work with it every day.
1. What is the DOM really? (The simplest honest explanation)
DOM = Document Object Model
The DOM is the structured, object-oriented representation of your web page (or any XML/HTML document) that the browser creates in memory.
When the browser reads your HTML (or XML), it does not just keep it as text. It turns the entire document into a live tree of objects that JavaScript can talk to, read from, change, add to, or remove from.
Real-life analogy everyone understands
Imagine your web page is a house:
- The HTML file is the blueprint / architectural plan written on paper
- The browser is the builder who reads the blueprint
- The DOM is the actual finished house — with real walls, doors, windows, furniture — that you can now walk around, repaint, add rooms to, or break things in.
JavaScript is the person living in the house who can:
- Open any door (find any element)
- Change the color of the walls (change styles / content)
- Move furniture (reorder elements)
- Build a new room (create elements)
- Throw out old furniture (remove elements)
The DOM is that live, interactive house — not the static blueprint.
2. The DOM Tree – Visualized (very important!)
Take this simple HTML:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<!DOCTYPE html> <html> <head> <title>My Page</title> </head> <body> <h1>Welcome</h1> <p id="intro">Hello <strong>world</strong>!</p> </body> </html> |
The browser turns it into this tree structure:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
Document └── html ├── head │ └── title │ └── Text: "My Page" └── body ├── h1 │ └── Text: "Welcome" └── p (id="intro") ├── Text: "Hello " └── strong └── Text: "world" └── Text: "!" |
Every box is a node.
Main types of nodes you will meet every day:
| Node type | What it represents | Example in the tree |
|---|---|---|
| Document | The entire document | The very top (root) |
| Element | Any tag: <div>, <p>, <h1>… | html, head, body, h1, p, strong |
| Text | Plain text inside elements | “Welcome”, “Hello “, “world”, “!” |
| Attribute | Attributes on elements | id=”intro” on the
|
| Comment | Not shown in simple examples |
3. How do we get the DOM in JavaScript?
The browser automatically gives us the DOM through one very important global object:
|
0 1 2 3 4 5 6 |
document |
document is your entry point to the entire DOM tree.
|
0 1 2 3 4 5 6 7 8 9 |
console.log(document); // → #document console.log(document.documentElement); // → <html> element (the real root) console.log(document.body); // → <body> element console.log(document.head); // → <head> element |
4. Most important ways to find things in the DOM (the tools you will use 95% of the time)
Method 1 – querySelector (modern & most useful)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
// First element that matches const h1 = document.querySelector("h1"); console.log(h1.textContent); // "Welcome" // Element with id const intro = document.querySelector("#intro"); console.log(intro.textContent); // "Hello world!" |
Method 2 – querySelectorAll (get many elements)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 |
const allParagraphs = document.querySelectorAll("p"); console.log(allParagraphs.length); // 1 // Loop over them allParagraphs.forEach(p => { console.log(p.textContent); }); |
Method 3 – getElementById (old but still very fast for IDs)
|
0 1 2 3 4 5 6 |
const intro = document.getElementById("intro"); |
Method 4 – getElementsByTagName / getElementsByClassName (older style)
|
0 1 2 3 4 5 6 7 |
const strongTags = document.getElementsByTagName("strong"); console.log(strongTags[0].textContent); // "world" |
Modern recommendation (2025–2026):
Use querySelector and querySelectorAll almost always — they are the most flexible and readable.
5. Reading & Changing Content
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
const h1 = document.querySelector("h1"); // Read console.log(h1.textContent); // "Welcome" console.log(h1.innerHTML); // "Welcome" // Change text (safest way) h1.textContent = "Hello Universe!"; // Change HTML (careful with user input – XSS risk!) h1.innerHTML = "Hello <strong>Universe</strong>!"; // Change style h1.style.color = "navy"; h1.style.backgroundColor = "#eff6ff"; |
6. Creating & Adding New Elements
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// 1. Create a new element const newP = document.createElement("p"); newP.textContent = "This paragraph was created by JavaScript!"; newP.style.color = "darkgreen"; // 2. Add it to the page document.body.appendChild(newP); // Alternative: insert at specific position document.body.insertBefore(newP, document.querySelector("h1").nextSibling); |
7. Removing Elements
|
0 1 2 3 4 5 6 7 8 9 10 |
const unwanted = document.querySelector("p"); if (unwanted) { unwanted.remove(); // Modern & clean // or old way: unwanted.parentNode.removeChild(unwanted); } |
8. Full Realistic Example – Load XML via AJAX & Work with DOM
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>AJAX + XML DOM – Practical Example</title> <style> body { font-family: Arial; margin: 40px; } button { padding: 12px 24px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer; } #output { margin-top: 30px; padding: 25px; background: #f0fdf4; border: 1px solid #86efac; border-radius: 8px; } </style> </head> <body> <h2>AJAX + XML DOM – Product Catalog</h2> <button onclick="loadCatalog()">Load Products from XML</button> <div id="output">Click to load catalog...</div> <script> async function loadCatalog() { const output = document.getElementById("output"); output.innerHTML = "Loading catalog..."; try { const response = await fetch("products.xml"); if (!response.ok) throw new Error(`HTTP {response.status}`); const xmlText = await response.text(); // Parse XML string into DOM const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlText, "application/xml"); if (xmlDoc.querySelector("parsererror")) { throw new Error("Invalid XML"); } // Now use DOM methods const products = xmlDoc.querySelectorAll("product"); let html = "<h3>Available Products</h3><ul>"; products.forEach(prod => { const name = prod.querySelector("name").textContent; const price = prod.querySelector("price").textContent; const curr = prod.querySelector("price").getAttribute("currency") || "USD"; html += `<li><strong>${name}</strong> – ${curr} ${price}</li>`; }); html += "</ul>"; output.innerHTML = html; } catch (err) { output.innerHTML = `<strong style="color:red">Error:</strong> ${err.message}`; } } </script> </body> </html> |
products.xml (same folder)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?xml version="1.0" encoding="UTF-8"?> <catalog> <product> <name>Wireless Mouse</name> <price currency="INR">1499.00</price> </product> <product> <name>Bluetooth Speaker</name> <price currency="INR">3499.00</price> </product> </catalog> |
Summary – XML DOM Quick Reference (keep this handy)
| Task | Code example |
|---|---|
| Parse string to DOM | new DOMParser().parseFromString(xml, “application/xml”) |
| Get root element | xmlDoc.documentElement |
| Find first element | xmlDoc.querySelector(“title”) |
| Find all matching elements | xmlDoc.querySelectorAll(“price”) |
| Get text | element.textContent |
| Get attribute | element.getAttribute(“currency”) |
| Change text | element.textContent = “New value” |
| Change attribute | element.setAttribute(“currency”, “USD”) |
| Create element | xmlDoc.createElement(“discount”) |
| Add child | parent.appendChild(newElement) |
| Remove element | element.remove() or parent.removeChild(element) |
Would you like to continue with any of these deeper topics?
- Namespaces in real XML DOM (very common in SOAP, RSS, e-invoice…)
- Creating & sending XML via AJAX
- Walking the tree manually (parentNode, childNodes, nextSibling…)
- Common bugs & debugging XML DOM parsing
- Modern parsing with fetch + DOMParser
- Real-world examples (RSS feed, SOAP response, config file…)
Just tell me which one you want to practice or understand more deeply! 😊
