JavaScript Document createTreeWalker() Method

Beginner
⏱️ 12 min read
📚 Updated: Jul 2026
🎯 5 Examples
🚀 5 Try-it labs
Baseline Widely available
Instance method

What You’ll Learn

document.createTreeWalker() is an instance method that returns a TreeWalker for walking a DOM subtree (see MDN Document: createTreeWalker()). Learn root, whatToShow, custom filters, nextNode() loops, tree moves like firstChild, how it compares to NodeIterator, and five try-it labs.

01

Kind

Instance method

02

Returns

TreeWalker

03

Start

root = currentNode

04

Filter

whatToShow

05

Walk with

nextNode()

06

Status

Baseline

Introduction

A TreeWalker is a cursor for a DOM branch. You pick a root, optionally filter which node types matter, then move with nextNode() — or step like a real tree using firstChild(), nextSibling(), and friends.

document.createTreeWalker(root, whatToShow, filter) builds that walker. MDN’s first example walks every text node under #root and uppercases node.data.

💡
Think: filtered tree cursor

1) Pick a root (becomes currentNode)
2) Limit types with whatToShow (optional)
3) Accept / reject / skip with a filter (optional)
4) Loop nextNode() or use tree moves

For simple element lists, querySelectorAll is often enough. Use TreeWalker when you need text/comment traversal or parent/sibling navigation.

Related tutorials: createNodeIterator(), nodeType, createTextNode().

Understanding document.createTreeWalker()

An instance method on the page’s document object (MDN Document interface).

  • root — node representing the walker root; initial TreeWalker.currentNode (MDN).
  • whatToShow — optional bitmask of NodeFilter show constants; default SHOW_ALL (MDN).
  • filter — optional callback or object with acceptNode() (MDN).
  • Return value — a new TreeWalker (MDN).
  • Document ordernextNode() / previousNode().
  • Tree movesparentNode, firstChild, lastChild, previousSibling, nextSibling.

📝 Syntax

General forms of Document.createTreeWalker (MDN):

JavaScript
createTreeWalker(root)
createTreeWalker(root, whatToShow)
createTreeWalker(root, whatToShow, filter)

Parameters

  • root — a Node that is the root of the TreeWalker and the initial currentNode (MDN).
  • whatToShow (optional) — unsigned long bitmask from NodeFilter constants. Defaults to 0xFFFFFFFF ((SHOW_ALL) (MDN).
  • filter (optional) — callback or { acceptNode() } returning FILTER_ACCEPT, FILTER_REJECT, or FILTER_SKIP (MDN).

Return value

A new TreeWalker object (MDN).

Filter return values (MDN)

  • FILTER_ACCEPT — include this node.
  • FILTER_REJECT — exclude this node and its subtree.
  • FILTER_SKIP — exclude this node only (descendants may still be visited).

Useful whatToShow flags

ConstantShows
NodeFilter.SHOW_ALLAll nodes (default)
NodeFilter.SHOW_ELEMENTElement nodes
NodeFilter.SHOW_TEXTText nodes
NodeFilter.SHOW_COMMENTComment nodes
NodeFilter.SHOW_DOCUMENTDocument nodes
NodeFilter.SHOW_DOCUMENT_FRAGMENTDocumentFragment nodes

Combine flags with |, for example NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT. MDN: SHOW_ATTRIBUTE is only useful when the root is an Attr node — prefer Element.attributes for attributes. Some older constants (SHOW_ENTITY, …) are legacy and no longer effective.

MDN example (whatToShow)

JavaScript
const treeWalker = document.createTreeWalker(
  document.querySelector("#root"),
  NodeFilter.SHOW_TEXT,
);

while (treeWalker.nextNode()) {
  const node = treeWalker.currentNode;
  node.data = node.data.toUpperCase();
}

⚡ Quick Reference

GoalCode
Create walkerdocument.createTreeWalker(root, NodeFilter.SHOW_TEXT)
Advancewhile (walker.nextNode()) { ... }
Current nodewalker.currentNode
First child movewalker.firstChild()
Accept in filterreturn NodeFilter.FILTER_ACCEPT
Reject subtreereturn NodeFilter.FILTER_REJECT
Skip node onlyreturn NodeFilter.FILTER_SKIP
MDN statusBaseline Widely available

🔍 At a Glance

Four facts about document.createTreeWalker().

Returns
TreeWalker

object

Root
currentNode

starts here

Filter
whatToShow

+ callback

Status
Baseline

since 2015

📋 FILTER_REJECT vs FILTER_SKIP (TreeWalker)

FILTER_REJECTFILTER_SKIP
Include this node?NoNo
Visit descendants?No (whole subtree excluded) (MDN)Yes, may still be visited (MDN)
Typical useSkip a branch entirelySkip a wrapper but keep children

Examples Gallery

Examples follow MDN Document: createTreeWalker() and practical TreeWalker patterns for beginners.

📚 Getting Started

Create a walker and loop with nextNode().

Example 1 — MDN: uppercase text with SHOW_TEXT

Walk every text node under #root and transform data.

JavaScript
const treeWalker = document.createTreeWalker(
  document.querySelector("#root"),
  NodeFilter.SHOW_TEXT,
);

while (treeWalker.nextNode()) {
  const node = treeWalker.currentNode;
  node.data = node.data.toUpperCase();
}

console.log(document.querySelector("#root").textContent);
Try It Yourself

How It Works

MDN notes descendant text nodes are visited even when they are not direct children of #root. SHOW_TEXT skips element nodes themselves.

Example 2 — Collect element tag names

Use SHOW_ELEMENT and push each tagName.

JavaScript
const root = document.querySelector("#demo");
const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);
const tags = [];

while (walker.nextNode()) {
  tags.push(walker.currentNode.tagName.toLowerCase());
}

console.log(tags.join(", "));
Try It Yourself

How It Works

After create, currentNode is the root. The first nextNode() moves to the next matching node in document order under that root.

📈 Practical Patterns

Tree moves, filters, and comparison with NodeIterator.

Example 3 — firstChild() and nextSibling()

Step like a tree instead of only document-order nextNode().

JavaScript
const root = document.querySelector("#list");
const walker = document.createTreeWalker(root, NodeFilter.SHOW_ELEMENT);

const first = walker.firstChild(); // first matching child of root
const names = [];
let node = first;
while (node) {
  names.push(node.tagName.toLowerCase());
  node = walker.nextSibling();
}

console.log(names.join(", "));
Try It Yourself

How It Works

This is the main reason to prefer TreeWalker over NodeIterator when you need sibling/parent navigation, not just a flat forward scan.

Example 4 — Custom filter (ACCEPT / REJECT / SKIP)

Simplified pattern inspired by MDN’s escape-filter example.

JavaScript
const walker = document.createTreeWalker(
  document.querySelector("#box"),
  NodeFilter.SHOW_ELEMENT,
  (node) => {
    if (node.classList.contains("skip-branch")) {
      return NodeFilter.FILTER_REJECT; // skip node + subtree
    }
    if (node.classList.contains("keep")) {
      return NodeFilter.FILTER_ACCEPT;
    }
    return NodeFilter.FILTER_SKIP; // skip wrapper, still visit children
  },
);

const kept = [];
while (walker.nextNode()) {
  kept.push(walker.currentNode.id || walker.currentNode.tagName);
}
console.log(kept.join(", "));
Try It Yourself

How It Works

MDN: FILTER_REJECT blocks the whole subtree; FILTER_SKIP ignores only that node.

Example 5 — Same walk with TreeWalker vs NodeIterator

Both can collect text with nextNode(); TreeWalker adds tree APIs.

JavaScript
const root = document.querySelector("#sample");

function collectText(factory) {
  const cursor = factory(root, NodeFilter.SHOW_TEXT);
  const parts = [];
  while (cursor.nextNode()) {
    const t = cursor.currentNode.data.trim();
    if (t) parts.push(t);
  }
  return parts.join(" | ");
}

console.log("walker:", collectText(document.createTreeWalker.bind(document)));
console.log("iterator:", collectText(document.createNodeIterator.bind(document)));
Try It Yourself

How It Works

For a plain forward text scan, either API works. Choose TreeWalker when you also need firstChild / parentNode-style moves.

🚀 Common Use Cases

  • Transform all text — MDN uppercase / encodeURI patterns.
  • Find comments or mixed node types — selectors cannot see comments.
  • Skip whole branchesFILTER_REJECT on a container.
  • Sibling navigation — walk only direct matching children.
  • Editors / highlighters — walk text nodes under a contenteditable root.
  • Teaching the DOM tree — contrast flat iterators with tree moves.

🧠 How createTreeWalker() Works

1

Pass a root

MDN: root is the initial currentNode.

Start
2

Apply whatToShow

Bitmask limits node kinds (default SHOW_ALL).

Type filter
3

Run acceptNode filter

ACCEPT, REJECT (subtree), or SKIP (node only) (MDN).

Custom
4

Move the cursor

Use nextNode() or tree methods on the TreeWalker.

📝 Notes

  • MDN: Baseline Widely available since July 2015.
  • Returns a TreeWalker; currentNode starts at root (MDN).
  • FILTER_REJECT skips a whole subtree; FILTER_SKIP skips one node (MDN).
  • SHOW_ATTRIBUTE is special — prefer Element.attributes (MDN).
  • Some older show constants are legacy and no longer effective (MDN).
  • Related: createNodeIterator(), nodeType, createTextNode().

Browser Support

Document.createTreeWalker() is Baseline Widely available on MDN (since July 2015). Logos use the shared browser-image-sprite.png sprite from this project.

Baseline Widely available

Document.createTreeWalker()

Create TreeWalker cursors for filtered DOM traversal across all major browsers.

Baseline Widely available
Google Chrome Supported
Yes
Mozilla Firefox Supported
Yes
Apple Safari Supported
Yes
Microsoft Edge Supported
Yes
Opera Supported
Yes
Internet Explorer Supported (legacy)
Yes
createTreeWalker() Wide

Bottom line: Use createTreeWalker when you need filtered subtree walks or parent/sibling navigation. Prefer querySelectorAll for simple element lists.

Conclusion

document.createTreeWalker(root, whatToShow, filter) returns a TreeWalker cursor for a DOM branch. Set whatToShow, optionally filter with ACCEPT / REJECT / SKIP, then walk with nextNode() or tree moves — just like MDN’s text-transform examples.

Continue with createNodeIterator(), elementFromPoint(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Choose a tight root so you do not walk the whole document
  • Use SHOW_TEXT / SHOW_ELEMENT instead of filtering everything in JS
  • Use FILTER_REJECT when a whole branch should be ignored (MDN)
  • Prefer TreeWalker when you need sibling/parent navigation
  • Prefer querySelectorAll for simple element queries

❌ Don’t

  • Confuse FILTER_REJECT with FILTER_SKIP (subtree vs node)
  • Rely on SHOW_ATTRIBUTE for normal element trees (MDN)
  • Forget that currentNode starts at the root
  • Mutate the tree carelessly while walking (can surprise the cursor)
  • Use TreeWalker when a CSS selector already answers the question

Key Takeaways

Knowledge Unlocked

Five things to remember about createTreeWalker()

Build a filtered DOM cursor with optional tree navigation.

5
Core concepts
📄02

Root

currentNode

start
🔎03

Filter

whatToShow

bitmask
⚖️04

Reject

skips subtree

MDN
🛡05

Status

Baseline

2015

❓ Frequently Asked Questions

MDN: Document.createTreeWalker() returns a newly created TreeWalker object rooted at a given Node, optionally filtered by whatToShow and a filter callback.
No. MDN marks Document.createTreeWalker() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
A new TreeWalker object (MDN). TreeWalker.currentNode starts as the root you passed in.
Both walk a filtered subtree. TreeWalker also supports tree-shaped moves such as parentNode, firstChild, lastChild, previousSibling, and nextSibling. Prefer createNodeIterator for a simple forward nextNode loop.
MDN: an optional bitmask from NodeFilter constants (for example SHOW_TEXT or SHOW_ELEMENT). It defaults to SHOW_ALL (0xFFFFFFFF).
MDN: FILTER_ACCEPT includes the node; FILTER_REJECT excludes that node and its whole subtree; FILTER_SKIP excludes only that node (descendants may still be visited).
Did you know?

On a NodeIterator, MDN treats FILTER_REJECT and FILTER_SKIP as equivalent. On a TreeWalker, they are different: reject cuts off the whole branch. That difference is one of the best reasons to learn both APIs.

Next: elementFromPoint()

Learn how to find the topmost Element at viewport x/y coordinates.

elementFromPoint() →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

7 people found this page helpful