JavaScript Document createNodeIterator() Method

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

What You’ll Learn

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

01

Kind

Instance method

02

Returns

NodeIterator

03

Start

root node

04

Filter

whatToShow

05

Walk with

nextNode()

06

Status

Baseline

Introduction

Sometimes you need every matching node under a branch of the tree — including text nodes or comments that CSS selectors ignore. A NodeIterator walks that subtree in document order.

document.createNodeIterator(root, whatToShow, filter) builds the iterator. Then you call nextNode() until it returns null. MDN’s example collects every <p> under document.body that passes a filter.

💡
Think: filtered tree walk

1) Pick a root
2) Limit types with whatToShow (optional)
3) Accept/skip with a filter (optional)
4) Loop nextNode()

For simple element lists, querySelectorAll is often enough. Use NodeIterator when you need node-type control or text/comment traversal.

Related tutorials: createExpression(), nodeType, createElement().

Understanding document.createNodeIterator()

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

  • root — node where traversal begins (MDN).
  • whatToShow — optional bitmask of NodeFilter show constants; default SHOW_ALL (MDN).
  • filter — optional callback or { acceptNode } object (MDN).
  • Return value — a new NodeIterator (MDN).
  • WalknextNode() / previousNode() move the cursor.
  • Reject vs skip — for this API, FILTER_REJECT and FILTER_SKIP are equivalent (MDN).

📝 Syntax

General forms of Document.createNodeIterator (MDN):

JavaScript
createNodeIterator(root)
createNodeIterator(root, whatToShow)
createNodeIterator(root, whatToShow, filter)

Parameters

  • root — the root node for the iterator’s traversal (MDN).
  • whatToShow (optional) — unsigned long bitmask from NodeFilter constants. Defaults to 0xFFFFFFFF ((SHOW_ALL) (MDN).
  • filter (optional) — a function, or an object with acceptNode(), returning FILTER_ACCEPT, FILTER_REJECT, or FILTER_SKIP (MDN).

Return value

A new NodeIterator object (MDN).

MDN example (callback filter)

JavaScript
const nodeIterator = document.createNodeIterator(
  document.body,
  NodeFilter.SHOW_ELEMENT,
  (node) =>
    node.nodeName.toLowerCase() === "p"
      ? NodeFilter.FILTER_ACCEPT
      : NodeFilter.FILTER_REJECT,
);
const pars = [];
let currentNode;

while ((currentNode = nodeIterator.nextNode())) {
  pars.push(currentNode);
}

📋 Common whatToShow constants

Useful NodeFilter show flags from MDN (not an exhaustive list):

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 bitwise OR, for example NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT.

💡
Attribute note (MDN)

SHOW_ATTRIBUTE is only effective when the root is an attribute node. Prefer Element.attributes to walk attributes.

⚡ Quick Reference

GoalCode
Create iteratordocument.createNodeIterator(root, NodeFilter.SHOW_ELEMENT)
Next matchiterator.nextNode()
Previous matchiterator.previousNode()
Accept in filterreturn NodeFilter.FILTER_ACCEPT
Skip nodereturn NodeFilter.FILTER_REJECT (or FILTER_SKIP)
MDN statusBaseline Widely available

🔍 At a Glance

Four facts about document.createNodeIterator().

Returns
NodeIterator

MDN

Walk
nextNode()

until null

Filter
whatToShow

+ acceptNode

Status
Baseline

since 2015

📋 Callback filter vs acceptNode object

Function callbackObject with acceptNode
Shape(node) => FILTER_*{ acceptNode(node) { ... } }
MDN examplesYesYes (same result)
Best forShort filtersReusable / named filters

Examples Gallery

Examples follow MDN Document: createNodeIterator() and everyday DOM traversal patterns.

📚 Getting Started

Collect elements with a filter, using both MDN styles.

Example 1 — MDN: collect every <p>

Callback filter + SHOW_ELEMENT + nextNode() loop.

JavaScript
const nodeIterator = document.createNodeIterator(
  document.body,
  NodeFilter.SHOW_ELEMENT,
  (node) =>
    node.nodeName.toLowerCase() === "p"
      ? NodeFilter.FILTER_ACCEPT
      : NodeFilter.FILTER_REJECT,
);

const pars = [];
let currentNode;
while ((currentNode = nodeIterator.nextNode())) {
  pars.push(currentNode);
}
console.log(pars.length);
Try It Yourself

How It Works

whatToShow limits candidates to elements; the filter keeps only p tags. nextNode() returns each accepted node in order.

Example 2 — MDN: same filter as an acceptNode object

Equivalent object form from MDN.

JavaScript
const nodeIterator = document.createNodeIterator(
  document.body,
  NodeFilter.SHOW_ELEMENT,
  {
    acceptNode(node) {
      return node.nodeName.toLowerCase() === "p"
        ? NodeFilter.FILTER_ACCEPT
        : NodeFilter.FILTER_REJECT;
    },
  },
);

const pars = [];
let currentNode;
while ((currentNode = nodeIterator.nextNode())) {
  pars.push(currentNode.textContent.trim());
}
console.log(pars);
Try It Yourself

How It Works

Behavior matches the callback form. Prefer whichever style your team finds clearer.

📈 Practical Patterns

Text nodes, combined show flags, and walking backward.

Example 3 — Walk text nodes under a root

CSS selectors cannot select text nodes; iterators can.

JavaScript
const root = document.getElementById("box");
const it = document.createNodeIterator(root, NodeFilter.SHOW_TEXT);

const chunks = [];
let node;
while ((node = it.nextNode())) {
  const t = node.nodeValue.trim();
  if (t) chunks.push(t);
}
console.log(chunks);
Try It Yourself

How It Works

SHOW_TEXT includes only text nodes. Skipping empty whitespace keeps the list readable.

Example 4 — Combine SHOW_ELEMENT | SHOW_COMMENT

Bitmask OR lets you accept more than one node type.

JavaScript
const root = document.getElementById("panel");
const mask = NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT;
const it = document.createNodeIterator(root, mask);

const kinds = [];
let node;
while ((node = it.nextNode())) {
  kinds.push(node.nodeType === Node.COMMENT_NODE ? "comment" : node.nodeName);
}
console.log(kinds);
Try It Yourself

How It Works

The bitmask is a convenient type filter before any custom acceptNode logic runs (MDN).

Example 5 — previousNode() after advancing

Move forward, then step back one accepted node.

JavaScript
const it = document.createNodeIterator(
  document.getElementById("list"),
  NodeFilter.SHOW_ELEMENT,
  (node) =>
    node.nodeName.toLowerCase() === "li"
      ? NodeFilter.FILTER_ACCEPT
      : NodeFilter.FILTER_REJECT,
);

const first = it.nextNode();
const second = it.nextNode();
const back = it.previousNode();

console.log(first.textContent, second.textContent, back.textContent);
// e.g. "One" "Two" "Two"
Try It Yourself

How It Works

After two nextNode calls, the reference node is the second li. previousNode() returns that same node again when stepping back from just past it — experiment in the try-it lab to feel the cursor.

🚀 Common Use Cases

  • Collect filtered elements — walk a branch and keep only certain tags (MDN p sample).
  • Text extraction — iterate SHOW_TEXT under a container.
  • Comment / PI scans — nodes CSS cannot select.
  • Custom accept rules — class names, data attributes, or content checks in acceptNode.
  • Not always needed — prefer querySelectorAll for simple element lists.
  • Need tree moves? — consider createTreeWalker instead.

🧠 How createNodeIterator() Works

1

Choose a root

MDN: traversal starts at this node’s subtree.

Root
2

Apply whatToShow

Bitmask keeps only selected node types (elements, text, …).

Types
3

Run the filter

Accept or skip each candidate; children still considered when skipped (MDN).

Filter
4

Loop nextNode()

Collect nodes until the iterator returns null.

📝 Notes

  • MDN: Baseline Widely available since July 2015.
  • For createNodeIterator, FILTER_REJECT and FILTER_SKIP are equivalent (MDN).
  • SHOW_ATTRIBUTE is special — prefer Element.attributes for attributes (MDN).
  • Some older show constants (SHOW_ENTITY, …) are legacy and no longer effective (MDN).
  • Iterator position matters when mixing nextNode and previousNode.
  • Related: createExpression(), nodeType, createDocumentFragment().

Browser Support

Document.createNodeIterator() 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.createNodeIterator()

Create NodeIterator objects for filtered DOM traversal in every major browser.

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
createNodeIterator() Wide

Bottom line: Use NodeIterator for filtered walks (including text/comments). Prefer querySelectorAll for simple element lists.

Conclusion

document.createNodeIterator(root, whatToShow, filter) builds a NodeIterator for walking a subtree with optional type and custom filters. Loop with nextNode() until null, and reach for querySelectorAll when you only need simple element matches.

Continue with createExpression(), createNSResolver(), or the JavaScript hub.

💡 Best Practices

✅ Do

  • Scope root to the smallest useful subtree
  • Use whatToShow before writing a heavy filter
  • Loop until nextNode() returns null
  • Prefer querySelectorAll for simple CSS matches
  • Use TreeWalker when you need richer navigation

❌ Don’t

  • Assume FILTER_REJECT prunes children here (it does not for NodeIterator; MDN)
  • Rely on SHOW_ATTRIBUTE for normal element trees (MDN)
  • Forget that text nodes exist between elements
  • Mutate the tree mid-walk without understanding live DOM effects
  • Overuse iterators where a selector is clearer

Key Takeaways

Knowledge Unlocked

Five things to remember about createNodeIterator()

Filtered DOM walks with nextNode().

5
Core concepts
🔄02

Walk

nextNode()

loop
📄03

Types

whatToShow

bitmask
⚖️04

Filter

acceptNode

optional
🛡05

Status

Baseline

2015

❓ Frequently Asked Questions

MDN: Document.createNodeIterator() returns a new NodeIterator for walking the DOM subtree starting at a root node. You usually call nextNode() in a loop until it returns null.
No. MDN marks Document.createNodeIterator() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
A new NodeIterator object (MDN).
MDN: an optional bitmask from NodeFilter constants (for example NodeFilter.SHOW_ELEMENT or SHOW_TEXT). It defaults to SHOW_ALL (0xFFFFFFFF).
MDN: a callback or an object with acceptNode() that returns FILTER_ACCEPT, FILTER_REJECT, or FILTER_SKIP. For createNodeIterator, FILTER_REJECT and FILTER_SKIP are equivalent — the node is skipped, but children continue to be considered.
Use TreeWalker when you need richer navigation (parentNode, firstChild, nextSibling, and so on). NodeIterator is a simpler forward/back iterator with nextNode() and previousNode().
Did you know?

On a TreeWalker, FILTER_REJECT can prune an entire subtree, but MDN notes that for createNodeIterator, FILTER_REJECT and FILTER_SKIP behave the same: the node is omitted, yet its children can still appear later in the walk.

Next: createNSResolver()

Learn the deprecated createNSResolver helper and modern XPath namespace resolvers.

createNSResolver() →

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