XML DOM Navigation
DOM navigation means moving through the node tree using parent-child and sibling relationships. The DOM provides properties on every node that point to neighboring nodes. Navigation is essential when you process complex XML structures where you need to move up, down, or sideways through the tree.
Navigation Properties
| Property | Returns |
|---|---|
| parentNode | The parent node |
| childNodes | NodeList of all child nodes |
| firstChild | The first child node |
| lastChild | The last child node |
| nextSibling | The next node at the same level |
| previousSibling | The previous node at the same level |
| firstElementChild | First child that is an element (skips text nodes) |
| lastElementChild | Last child that is an element |
| nextElementSibling | Next sibling that is an element |
| previousElementSibling | Previous sibling that is an element |
Navigation Example
var catalog = xmlDoc.documentElement;
// First child (may be a text/whitespace node)
var first = catalog.firstChild;
// First element child (skips whitespace text nodes)
var firstProduct = catalog.firstElementChild;
console.log(firstProduct.nodeName); // "product"
// Move to the next product sibling
var secondProduct = firstProduct.nextElementSibling;
console.log(secondProduct.getAttribute("id")); // "P002"
// Move back
var backToFirst = secondProduct.previousElementSibling;
// Go up to parent
var parent = firstProduct.parentNode;
console.log(parent.nodeName); // "catalog"
Navigating Through All Children
var book = xmlDoc.getElementsByTagName("book")[0];
var children = book.childNodes;
for (var i = 0; i < children.length; i++) {
var child = children[i];
// Skip whitespace text nodes
if (child.nodeType === 1) {
console.log(child.nodeName + ": " + child.textContent);
}
}
Key Points to Remember
- parentNode, childNodes, firstChild, lastChild, nextSibling, previousSibling navigate the full node tree including text nodes.
- firstElementChild, nextElementSibling, and similar properties skip text nodes — preferred for element-only navigation.
- Always check nodeType === 1 before reading nodeName or accessing child elements when using childNodes.
- Navigation properties return null when no matching node exists.
