Home >Web Front-end >JS Tutorial >TreeWalker: A Practical Guide to DOM Traversal

TreeWalker: A Practical Guide to DOM Traversal

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-23 01:02:11690browse

Recently I've started working on a new Chrome extension in my free time and in the research on how to handle some of the functionalities, I've started discovering more and more functionalities that JS has in dealing with the DOM of the page.

Given how an overwhelming number of people using JS are using it only through a framework, this would make an interesting topic for a series of short articles for people to learn a bit more about the underlying technologies that the frameworks they rely on are actually using.

We've all been there — you need to find specific elements in the DOM, but querySelector and getElementsBy* aren't quite cutting it. Maybe you need to find all text nodes containing a specific phrase, or you want to traverse elements matching certain conditions while skipping others. Enter TreeWalker - a powerful but often overlooked DOM traversal API.

What is TreeWalker?

TreeWalker is a DOM interface that lets you efficiently traverse and filter DOM nodes. Think of it as a more powerful and flexible alternative to methods like querySelector. While querySelector gives you elements matching a CSS selector, TreeWalker lets you:

  • Navigate the DOM tree in any direction (forward, backward, up, down)
  • Filter nodes based on custom conditions
  • Skip certain parts of the tree entirely
  • Access text nodes directly (something querySelector can't do)

Creating a TreeWalker

Let's start with a basic example:

const walker = document.createTreeWalker(
    document.body, // Root node to start traversal
    NodeFilter.SHOW_TEXT, // Only show text nodes
    {
        acceptNode: function(node) {
            // Only accept text nodes that aren't empty
            return node.textContent.trim().length > 0
                ? NodeFilter.FILTER_ACCEPT
                : NodeFilter.FILTER_REJECT;
        }
    }
);

The three parameters are:

  1. Root node — where to start traversing
  2. What types of nodes to show (text, elements, comments, etc.)
  3. A filter function that decides which nodes to accept or reject

Real World Examples

1. Find and Replace Text

Here's something you'll actually use — finding and replacing text while preserving HTML structure.

function replaceText(root, search, replace) {
    const walker = document.createTreeWalker(
        root,
        NodeFilter.SHOW_TEXT,
        {
            acceptNode: function(node) {
                return node.textContent.includes(search)
                    ? NodeFilter.FILTER_ACCEPT
                    : NodeFilter.FILTER_REJECT;
            }
        }
    );

    let node;
    while (node = walker.nextNode()) {
        node.textContent = node.textContent.replace(search, replace);
    }
}

// Usage
replaceText(document.body, 'old text', 'new text');

This is much more efficient than using innerHTML and won't break event listeners or form input values.

2. Custom DOM Query

Need to find elements matching complex conditions? TreeWalker has you covered. Let's build something more complex — say you need to find all elements that contain specific text, but only if they're inside

elements with a certain class, and ignore any that are inside
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn