Skip to content
Tutorials Center
My learning

Topics

Lesson 90 of 156 ยท The DOM

Traversing the DOM

Move around the DOM tree with parentElement, children and siblings, learn element vs node properties, and walk trees with recursion and TreeWalker.

Selectors are great when you know what you are looking for. But often you already have an element and need something relative to it: its parent, the next item in the list, the label just before it, the first cell in its row. Moving around the tree like this is called traversal.

The DOM gives every node a set of links to its neighbors. In this lesson you will learn the two families of those links โ€” one that sees every node and one that sees only elements โ€” and when to use each. Then you will walk entire subtrees, first with your own recursive function and then with the browser's built-in TreeWalker, and finish with a practical example: keyboard navigation between siblings.

Two families of properties

Recall from The DOM that the tree contains elements, but also text nodes (including whitespace between tags) and comments. Traversal properties come in pairs, one for all nodes and one for elements only:

Direction All nodes Elements only
Up parentNode parentElement
Down (all) childNodes children
First child firstChild firstElementChild
Last child lastChild lastElementChild
Next sibling nextSibling nextElementSibling
Previous sibling previousSibling previousElementSibling
Count childNodes.length childElementCount

The "all nodes" properties come from the Node interface; the element-only ones are newer and come from Element and related mixins. In everyday code, reach for the element-only versions. The node versions trip you up with whitespace:

Node vs element properties

nextSibling lands on the whitespace text node after </li>, while nextElementSibling skips straight to the next element โ€” and also skips the comment. Removing the whitespace from your HTML would change what the node properties return, which is a good reason not to depend on them.

Moving up

parentElement gives you the direct parent. It differs from parentNode in just one place: the <html> element's parentNode is document, but its parentElement is null, because document is not an element.

To go up more than one level, don't chain parentElement.parentElement.parentElement. That breaks the moment someone wraps an element in an extra <div>. Use closest(selector) from Selecting Elements instead; it finds the nearest ancestor that means something, however deep it is.

Two related checks are handy:

  • ancestor.contains(node) โ€” true if node is inside ancestor (or is ancestor itself).
  • a.compareDocumentPosition(b) โ€” a bitmask telling you whether b comes before or after a, contains it or is contained by it. Rarely needed, but useful for sorting nodes in document order.

Moving down and sideways

children gives you a live HTMLCollection of child elements. For direct children that match a selector, element.querySelectorAll(":scope > .item") is often clearer than filtering children by hand.

Siblings are where traversal really shines. Tab bars, carousels, menus, table cells and steps in a wizard all need "the next one" and "the previous one". nextElementSibling and previousElementSibling return null at the ends, which makes wrapping around easy:

JavaScript
const next = current.nextElementSibling ?? current.parentElement.firstElementChild;

The ?? operator falls back to the first child when there is no next sibling.

Example: arrow-key navigation

Here is a classic use: a toolbar where the arrow keys move focus between buttons. Each button finds its neighbor through sibling links; Home and End jump to the first and last child. Only the active button is in the Tab order (tabindex="0"), which is the "roving tabindex" pattern described in Keyboard Access and Focus.

Arrow keys with sibling traversal

Walking a whole tree with recursion

Sometimes you need to visit every descendant: count words, find all text matching a phrase, build an outline. A tree is naturally recursive โ€” each child is the root of a smaller tree โ€” so a recursive function is a natural fit:

JavaScript
function walk(node, visit, depth = 0) {
  visit(node, depth);
  for (const child of node.children) {
    walk(child, visit, depth + 1);
  }
}

Swap children for childNodes if you also need text nodes. Here it is building a nested outline of a document's headings and sections:

A recursive outline

For very deep trees, recursion can hit the call stack limit, but real pages are rarely deeper than a few dozen levels, so this is safe in practice.

TreeWalker: the built-in walker

The browser has a purpose-built tool for walking trees: document.createTreeWalker(root, whatToShow, filter). It visits nodes in document order and lets you choose which kinds of node to visit with a NodeFilter constant:

  • NodeFilter.SHOW_ELEMENT โ€” only elements.
  • NodeFilter.SHOW_TEXT โ€” only text nodes.
  • NodeFilter.SHOW_COMMENT โ€” only comments.
  • NodeFilter.SHOW_ALL โ€” everything. Constants can be combined with |.

An optional filter function returns NodeFilter.FILTER_ACCEPT, FILTER_SKIP (skip this node but visit its children) or FILTER_REJECT (skip it and its children). You move with walker.nextNode(), which returns null at the end; parentNode(), firstChild(), nextSibling() and friends exist too.

TreeWalker is especially good at finding text nodes, which no selector can match. That makes it the right tool for highlighting search terms:

Highlighting text with TreeWalker

Two techniques here are worth copying. First, the walker collects matching nodes, and the tree is changed only afterwards; changing nodes while a walker is standing on them makes it lose its place. Second, each text node is replaced by a mix of strings and <mark> elements with replaceWith(), so the user's search term is never parsed as HTML. The escaping uses RegExp.escape(), a recent addition, with a fallback for older browsers; Regular Expressions covers patterns in depth.

There is also a simpler cousin, document.createNodeIterator(), which takes the same arguments but only moves forward and backward through a flat sequence. TreeWalker can do everything it does and more.

Choosing a traversal tool

Task Tool
The nearest ancestor of a certain kind closest()
Direct parent parentElement
Neighbors in a list or toolbar nextElementSibling, previousElementSibling
First or last child element firstElementChild, lastElementChild
All descendant elements matching a selector querySelectorAll()
Every descendant, with custom logic A recursive function
Text nodes, or filtered walks TreeWalker

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In nicely indented HTML, what does li.nextSibling usually return?

    The node-level properties include text nodes, and the indentation between tags is text. nextElementSibling skips to the next element.
  2. 2. What is document.documentElement.parentElement?

    parentNode of <html> is document, but parentElement only returns elements, so it is null.
  3. 3. Why is button.closest(".card") better than button.parentElement.parentElement?

    closest() describes what you want rather than how many levels up it is, so it survives markup changes.
  4. 4. Which tool can find text nodes containing a word?

    Selectors only match elements. A TreeWalker with SHOW_TEXT visits every text node in document order.
  5. 5. How do you move to the next item, wrapping to the first one at the end?

    nextElementSibling is null after the last item, so ?? falls back to the parent's first element child.

Summary

  • Traversal properties come in pairs: node versions (parentNode, childNodes, nextSibling) include text and comments; element versions (parentElement, children, nextElementSibling) skip them. Prefer the element versions.
  • Go up with parentElement for one level and closest() for a meaningful ancestor; check containment with contains().
  • Sibling properties return null at the ends, which makes wrap-around navigation simple with ??.
  • Walk whole subtrees with a recursive function, or with TreeWalker when you need text nodes or filters.
  • Collect nodes first and modify the tree afterwards, and insert text with strings or textContent, never by parsing user input.

You have finished the DOM chapter. Next: The Browser Object Model โ€” window, location, history and the other objects the browser gives your scripts.