XML DOM Traversing
Traversing means visiting nodes one after another — usually every node in a subtree, or every child of an element. You traverse when you don't know the exact structure in advance: converting an unknown document to another format, counting things, searching for text, or printing an outline.
Looping over children
The simplest traversal visits the direct children of one element. Remember the white-space text nodes:
<!DOCTYPE html>
<html>
<body>
<script>
const xml = `<book id="b1">
<title>The Hobbit</title>
<author>J. R. R. Tolkien</author>
<year>1937</year>
</book>`;
const book = new DOMParser().parseFromString(xml, 'application/xml').documentElement;
console.log('All child nodes:');
for (const n of book.childNodes) console.log(' ', n.nodeName);
console.log('Element children only:');
for (const el of book.children) console.log(' ', el.nodeName, '=', el.textContent);
</script>
</body>
</html>Recursive traversal (depth-first)
To visit every node in a tree, write a function that handles one node and then calls itself for each child. This is called depth-first order: you go all the way down one branch before moving to the next.
<!DOCTYPE html>
<html>
<body>
<script>
const xml = `<library>
<section name="Fiction">
<book><title>The Hobbit</title><year>1937</year></book>
<book><title>Cien años de soledad</title><year>1967</year></book>
</section>
<section name="Science">
<book><title>A Brief History of Time</title><year>1988</year></book>
</section>
</library>`;
const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');
function outline(el, depth = 0) {
const label = el.getAttribute('name') ? ` (${el.getAttribute('name')})` : '';
const leafText = el.children.length === 0 ? `: ${el.textContent}` : '';
console.log(' '.repeat(depth) + el.nodeName + label + leafText);
for (const child of el.children) outline(child, depth + 1);
}
outline(xmlDoc.documentElement);
</script>
</body>
</html>Collecting results while traversing
Traversal is often used to compute something. This version counts how often each element name occurs and gathers the leaf text:
<!DOCTYPE html>
<html>
<body>
<script>
const xml = `<library>
<book><title>The Hobbit</title><author>J. R. R. Tolkien</author></book>
<book><title>A Brief History of Time</title><author>Stephen Hawking</author></book>
<magazine><title>New Scientist</title></magazine>
</library>`;
const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');
const counts = {};
const leaves = [];
(function walk(node) {
if (node.nodeType === Node.ELEMENT_NODE) {
counts[node.nodeName] = (counts[node.nodeName] || 0) + 1;
if (node.children.length === 0) leaves.push(node.textContent);
}
for (const child of node.childNodes) walk(child);
})(xmlDoc.documentElement);
console.log(counts);
console.log(leaves.join(' / '));
</script>
</body>
</html>TreeWalker: traversal without recursion
The DOM has a built-in iterator, document.createTreeWalker(root, whatToShow, filter). It visits nodes in document order and can filter by type — for instance, only text nodes:
<!DOCTYPE html>
<html>
<body>
<script>
const xml = `<note><to>Ana</to><body>Meet at <time>10:00</time> by the <place>fountain</place>.</body></note>`;
const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');
const walker = xmlDoc.createTreeWalker(xmlDoc.documentElement, NodeFilter.SHOW_TEXT);
const pieces = [];
while (walker.nextNode()) pieces.push(JSON.stringify(walker.currentNode.nodeValue));
console.log('Text nodes in order:', pieces.join(', '));
const elWalker = xmlDoc.createTreeWalker(xmlDoc.documentElement, NodeFilter.SHOW_ELEMENT);
const names = [elWalker.currentNode.nodeName];
while (elWalker.nextNode()) names.push(elWalker.currentNode.nodeName);
console.log('Elements in order:', names.join(' → '));
</script>
</body>
</html>whatToShow flag |
Visits |
|---|---|
NodeFilter.SHOW_ALL |
Every node |
NodeFilter.SHOW_ELEMENT |
Elements |
NodeFilter.SHOW_TEXT |
Text nodes |
NodeFilter.SHOW_COMMENT |
Comments |
Flags can be combined with |, e.g. SHOW_ELEMENT | SHOW_TEXT.
Tip: Recursion is easiest to read;
TreeWalkeravoids deep call stacks on huge documents and lets you pause and resume traversal. For selecting specific nodes rather than visiting all of them, XPath orquerySelectorAllis shorter.
Test yourself
In depth-first traversal, which is visited first?
- All children of the root, then all grandchildren
- A node, then its whole first branch, before its next sibling
- Leaves before their parents
- Nodes in random order
Which TreeWalker flag visits only text nodes?
NodeFilter.SHOW_ELEMENTNodeFilter.SHOW_TEXTNodeFilter.TEXT_ONLYNode.TEXT_NODE