Chapter 48: DOM Examples
XML DOM Examples — written as if I’m your patient teacher sitting next to you, explaining everything slowly, clearly, and step-by-step.
We will go through progressively more realistic examples, starting from the absolute basics and gradually reaching real-world patterns you will actually encounter.
Every example comes with:
- Full copy-paste-ready code
- Step-by-step explanation
- What you see in the browser
- What happens in the DOM tree
- Common mistakes people make
- Why we write it this way in practice
Preparation: Tiny XML we will use in most examples
Save this as catalog.xml (or paste it into a string):
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?xml version="1.0" encoding="UTF-8"?> <catalog> <product id="P001" category="electronics"> <name>Wireless Mouse</name> <price currency="INR">1499.00</price> <stock>45</stock> <description>Ergonomic mouse with RGB lighting</description> </product> <product id="P002" category="accessories"> <name>USB-C Hub</name> <price currency="INR">2499.00</price> <stock>12</stock> </product> </catalog> |
Example 1 – The absolute simplest: Parse string → access one value
|
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 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>XML DOM Example 1 – Parse & Read</title> <style> body { font-family: Arial, sans-serif; margin: 40px; line-height: 1.6; } pre { background: #f8f9fa; padding: 20px; border-radius: 8px; white-space: pre-wrap; } </style> </head> <body> <h2>Example 1 – Parse XML string & read values</h2> <button onclick="parseAndShow()">Parse & Show Product Info</button> <pre id="output">Click the button...</pre> <script> function parseAndShow() { const xmlString = `<?xml version="1.0" encoding="UTF-8"?> <catalog> <product id="P001"> <name>Wireless Mouse</name> <price currency="INR">1499.00</price> <stock>45</stock> </product> </catalog>`; const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlString, "application/xml"); // Check if parsing failed if (xmlDoc.querySelector("parsererror")) { document.getElementById("output").textContent = "XML is invalid!"; return; } // Access nodes const product = xmlDoc.querySelector("product"); const name = product.querySelector("name").textContent; const price = product.querySelector("price").textContent; const currency = product.querySelector("price").getAttribute("currency"); const stock = product.querySelector("stock").textContent; document.getElementById("output").textContent = `Product found: - ID: ${product.getAttribute("id")} - Name: ${name} - Price: ${price} {currency} - Stock: ${stock}`; } </script> </body> </html> |
What happens inside the browser?
- parseFromString turns the string into a live DOM Document
- querySelector finds the first matching element
- textContent gets all text inside (including children)
- getAttribute reads attribute values
Most common beginner mistake here
|
0 1 2 3 4 5 6 7 |
console.log(product.name); // undefined — wrong! console.log(product.getAttribute("name")); // null — wrong! |
Correct: product.querySelector(“name”).textContent
Example 2 – Load XML via fetch + show all products in a list
|
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 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>XML DOM Example 2 – Load from file & list products</title> <style> body { font-family: Arial; margin: 40px; } button { padding: 12px 24px; background: #10b981; color: white; border: none; border-radius: 6px; cursor: pointer; } #products { margin-top: 30px; } .product { margin: 16px 0; padding: 16px; background: #ecfdf5; border: 1px solid #a7f3d0; border-radius: 8px; } </style> </head> <body> <h2>Example 2 – Load XML file via fetch & display products</h2> <button onclick="loadProducts()">Load catalog.xml</button> <div id="products">Click to load...</div> <script> async function loadProducts() { const container = document.getElementById("products"); container.innerHTML = "Loading catalog..."; try { const response = await fetch("catalog.xml"); if (!response.ok) throw new Error(`HTTP {response.status}`); const xmlText = await response.text(); const parser = new DOMParser(); const xmlDoc = parser.parseFromString(xmlText, "application/xml"); if (xmlDoc.querySelector("parsererror")) { throw new Error("Invalid XML"); } const products = xmlDoc.querySelectorAll("product"); if (products.length === 0) { container.innerHTML = "<strong>No products found</strong>"; return; } let html = ""; products.forEach(product => { const id = product.getAttribute("id"); const name = product.querySelector("name")?.textContent || "No name"; const priceEl = product.querySelector("price"); const price = priceEl?.textContent || "N/A"; const currency = priceEl?.getAttribute("currency") || "?"; const stock = product.querySelector("stock")?.textContent || "N/A"; html += ` <div class="product"> <strong>${name}</strong><br> ID: ${id}<br> Price: ${price} ${currency}<br> Stock: ${stock} </div>`; }); container.innerHTML = html; } catch (err) { container.innerHTML = `<strong style="color:red">Error:</strong> ${err.message}`; } } </script> </body> </html> |
catalog.xml (same folder)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<?xml version="1.0" encoding="UTF-8"?> <catalog> <product id="P001" category="electronics"> <name>Wireless Mouse</name> <price currency="INR">1499.00</price> <stock>45</stock> </product> <product id="P002" category="accessories"> <name>USB-C Hub</name> <price currency="INR">2499.00</price> <stock>12</stock> </product> </catalog> |
Example 3 – Modify & add new nodes after loading
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
// Continuing from previous example... function addDiscountToAll() { const products = xmlDoc.querySelectorAll("product"); products.forEach(product => { const discount = xmlDoc.createElement("discount"); discount.setAttribute("type", "welcome"); discount.textContent = "10% off this week"; product.appendChild(discount); }); // Show updated XML const serializer = new XMLSerializer(); output.textContent = serializer.serializeToString(xmlDoc); } |
Summary – XML DOM Practical Cheat Sheet
| Task | Typical code pattern | Important notes / traps |
|---|---|---|
| Load XML from string | new DOMParser().parseFromString(xmlString, “application/xml”) | Always check parsererror |
| Load XML via fetch | await fetch(“file.xml”).then(r => r.text()) → parse | Use response.text() — not .xml() |
| Find one element | xmlDoc.querySelector(“product”) | Returns first match or null |
| Find many elements | xmlDoc.querySelectorAll(“product”) | Returns static NodeList |
| Get text safely | `element?.textContent?.trim() | |
| Get attribute | element.getAttribute(“id”) | Returns null if missing |
| Loop over products | products.forEach(product => …) | Modern & clean |
| Convert NodeList → real array | Array.from(products) or […products] | Needed for .map, .filter, etc. |
| Add new element | const el = xmlDoc.createElement(“discount”) → parent.appendChild(el) | Always create from the same document |
Would you like to continue with one of these next?
- Creating & adding new products dynamically
- Modifying existing values (change prices, add attributes)
- Removing nodes (delete out-of-stock products)
- Cloning nodes (duplicate products)
- Working with namespaces (real e-invoice, SOAP, RSS examples)
- Saving modified XML back as string or file
Just tell me which direction you want to go next! 😊
