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

PropertyReturns
parentNodeThe parent node
childNodesNodeList of all child nodes
firstChildThe first child node
lastChildThe last child node
nextSiblingThe next node at the same level
previousSiblingThe previous node at the same level
firstElementChildFirst child that is an element (skips text nodes)
lastElementChildLast child that is an element
nextElementSiblingNext sibling that is an element
previousElementSiblingPrevious 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.

Leave a Comment

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