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):

XML

Example 1 – The absolute simplest: Parse string → access one value

HTML

What happens inside the browser?

  1. parseFromString turns the string into a live DOM Document
  2. querySelector finds the first matching element
  3. textContent gets all text inside (including children)
  4. getAttribute reads attribute values

Most common beginner mistake here

JavaScript

Correct: product.querySelector(“name”).textContent

Example 2 – Load XML via fetch + show all products in a list

HTML

catalog.xml (same folder)

XML

Example 3 – Modify & add new nodes after loading

JavaScript

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! 😊

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *