TExcelTAD
Home › XML › DOM Navigating

XML DOM Navigating

Navigating means moving from one node to a related one: up to the parent, down to a child, sideways to a sibling. Each node has properties for this. There are two families — one that includes all nodes (text, comments …) and one that sees elements only.

Navigation properties

Direction Any node Elements only
Up parentNode parentElement
First child firstChild firstElementChild
Last child lastChild lastElementChild
All children childNodes children
Next sibling nextSibling nextElementSibling
Previous sibling previousSibling previousElementSibling
text
                   library
                 ┌────┴────┐
              book b1    book b2        ← siblings
             ┌──┴──┐     ┌──┴──┐
          title  year  title  year      ← title is book's firstElementChild

The white-space problem

With indented XML, firstChild of <book> is usually a text node containing a newline — not the <title> you expected:

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xml = `<library>
  <book id="b1">
    <title>The Hobbit</title>
    <year>1937</year>
  </book>
  <book id="b2">
    <title>A Brief History of Time</title>
    <year>1988</year>
  </book>
</library>`;
    const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');
    const book = xmlDoc.querySelector('book');

    console.log('firstChild        :', book.firstChild.nodeName);
    console.log('firstElementChild :', book.firstElementChild.nodeName);
    console.log('nextSibling       :', book.nextSibling.nodeName);
    console.log('nextElementSibling:', book.nextElementSibling.nodeName, book.nextElementSibling.getAttribute('id'));
  </script>
</body>
</html>

Before firstElementChild and friends existed, programmers wrote helper functions that skipped text nodes manually. You'll still see them in older code:

js
function firstElement(node) {
  let x = node.firstChild;
  while (x && x.nodeType !== 1) x = x.nextSibling;
  return x;
}

Today, just use the …Element… properties.

Moving around step by step

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xml = `<library>
  <book id="b1"><title>The Hobbit</title><author>J. R. R. Tolkien</author><year>1937</year></book>
  <book id="b2"><title>A Brief History of Time</title><author>Stephen Hawking</author><year>1988</year></book>
  <book id="b3"><title>Cien años de soledad</title><author>Gabriel García Márquez</author><year>1967</year></book>
</library>`;
    const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');
    const lib = xmlDoc.documentElement;

    const last = lib.lastElementChild;
    console.log('Last book        :', last.getAttribute('id'));
    console.log('Its title        :', last.firstElementChild.textContent);
    console.log('Its year         :', last.lastElementChild.textContent);
    console.log('Book before it   :', last.previousElementSibling.getAttribute('id'));

    const author = last.querySelector('author');
    console.log('Author → parent → previous → author:',
      author.parentElement.previousElementSibling.querySelector('author').textContent);
    console.log('Up to the document:', author.parentNode.parentNode.parentNode.nodeName);
  </script>
</body>
</html>

Walking all siblings

A while loop with nextElementSibling visits every following sibling until it runs out (null):

html · try it yourself
<!DOCTYPE html>
<html>
<body>
  <script>
    const xml = `<playlist>
      <track>Intro</track><track>Blue Hour</track><track>Rain Song</track><track>Outro</track>
    </playlist>`;
    const xmlDoc = new DOMParser().parseFromString(xml, 'application/xml');

    let n = 1;
    for (let t = xmlDoc.documentElement.firstElementChild; t; t = t.nextElementSibling) {
      console.log(`${n++}. ${t.textContent}`);
    }

    // Find the track after "Blue Hour"
    const blue = [...xmlDoc.querySelectorAll('track')].find(t => t.textContent === 'Blue Hour');
    console.log('Next after Blue Hour:', blue.nextElementSibling.textContent);
  </script>
</body>
</html>

closest() — going up with a selector

element.closest(selector) walks up from the element (starting with itself) and returns the first ancestor that matches, or null:

js
const yearEl = xmlDoc.querySelector('year');
const book = yearEl.closest('book');        // the enclosing <book>
console.log(book.getAttribute('id'));

Tip: Navigation properties return null at the edges of the tree (no parent, no next sibling…). Use optional chaining — node.nextElementSibling?.textContent — when the neighbour might not exist.

Test yourself

In indented XML, what is book.firstChild usually?

  1. The first child element
  2. A whitespace text node
  3. The first attribute
  4. null

Which property returns the next sibling **element**, skipping text?

  1. nextSibling
  2. nextElementSibling
  3. nextNode
  4. siblingElement

What does lastElementChild.previousElementSibling return for an element with three child elements?

  1. The first child
  2. The second child
  3. The third child
  4. null