JavaScript NodeIterator nextNode() Method

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

What You’ll Learn

The nextNode() method of a NodeIterator returns the next node in document order and advances the iterator. Learn the first-call behavior, null at the end, common while loops, and how it works with filter and whatToShow—with five examples and try-it labs.

01

Kind

Instance method

02

Returns

Node or null

03

Params

None

04

Direction

Forward

05

Updates

referenceNode

06

Status

Baseline widely

Introduction

After you create a NodeIterator with document.createNodeIterator(root, whatToShow, filter), you walk the subtree by calling nextNode(). Each call moves one step forward in document order.

The first call to nextNode() returns the first node in the set. When there are no more nodes, it returns null—the usual signal to stop looping.

💡
Beginner tip

The classic pattern is while ((node = it.nextNode())) { ... }. Check for null to know when the walk is finished.

Understanding the nextNode() Method

An instance method on NodeIterator that returns the next node in the iterator’s set and advances the iterator position.

  • Returns — a Node, or null when done.
  • Parameters — none.
  • First call — returns the first node in the set (MDN).
  • Advances — updates referenceNode and pointerBeforeReferenceNode.
  • RespectswhatToShow bitmask and filter.acceptNode().
  • Baseline Widely available on MDN (since July 2015).

📝 Syntax

Call the method on a NodeIterator:

JavaScript
nodeIterator.nextNode()

Parameters

None.

Return value

A Node representing the next node in the set, or null if the current node is the last one.

Typical pattern (MDN idea)

JavaScript
const nodeIterator = document.createNodeIterator(
  document.body,
  NodeFilter.SHOW_ELEMENT,
  {
    acceptNode(node) {
      return NodeFilter.FILTER_ACCEPT;
    },
  },
);

const currentNode = nodeIterator.nextNode(); // first node in the set

⚡ Quick Reference

GoalCode / note
Next nodeiterator.nextNode()
Loop allwhile ((n = it.nextNode())) { ... }
First nodeFirst nextNode() call
End of walkReturns null
ParametersNone
MDN statusBaseline Widely available (since July 2015)

🔍 At a Glance

Four facts to remember about NodeIterator.nextNode().

Returns
Node|null

Next or done

Params
none

No arguments

Direction
forward

Document order

Baseline
widely

Since Jul 2015

Examples Gallery

Examples follow MDN NodeIterator.nextNode. Labs walk real DOM subtrees with SHOW_ELEMENT and custom filters.

📚 Getting Started

First call and basic forward walks.

Example 1 — First nextNode() Call (MDN Idea)

Create an iterator on document.body and get the first element node.

JavaScript
const nodeIterator = document.createNodeIterator(
  document.body,
  NodeFilter.SHOW_ELEMENT,
  { acceptNode: () => NodeFilter.FILTER_ACCEPT },
);

const currentNode = nodeIterator.nextNode();
console.log(currentNode.nodeName); // e.g. "HTML" or first element in set
Try It Yourself

How It Works

MDN: the first nextNode() returns the first node in the iterator’s set, not the second.

Example 2 — while Loop Until null

Keep calling nextNode() until the walk is finished.

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

let count = 0;
let node;
while ((node = it.nextNode())) {
  count++;
}
console.log(count); // number of element nodes visited
Try It Yourself

How It Works

When nextNode() returns null, the while condition is falsy and the loop stops.

📈 Practical Patterns

Collect data and combine with iterator properties.

Example 3 — Collect Element Tag Names

Build an array of nodeName values from a subtree.

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

const tags = [];
let node;
while ((node = it.nextNode())) {
  tags.push(node.nodeName);
}
console.log(tags); // ["DIV", "SPAN", "SPAN"]
Try It Yourself

How It Works

SHOW_ELEMENT skips text nodes; only element tags appear in the array.

Example 4 — nextNode() Updates referenceNode

Each step moves the iterator anchor forward.

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

const first = it.nextNode();
console.log(it.referenceNode === first); // true

const second = it.nextNode();
console.log(it.referenceNode === second); // true
Try It Yourself

How It Works

See also referenceNodenextNode() is what moves it during forward walks.

Example 5 — nextNode() With a Custom Filter

Only nodes accepted by filter.acceptNode() are returned.

JavaScript
const it = document.createNodeIterator(
  document.getElementById("box"),
  NodeFilter.SHOW_ELEMENT,
  {
    acceptNode(node) {
      return node.classList.contains("pick")
        ? NodeFilter.FILTER_ACCEPT
        : NodeFilter.FILTER_REJECT;
    },
  },
);

const picked = [];
let node;
while ((node = it.nextNode())) {
  picked.push(node.textContent.trim());
}
console.log(picked); // ["A", "B"]
Try It Yourself

How It Works

nextNode() skips rejected nodes automatically—you only see FILTER_ACCEPT results.

🚀 Common Use Cases

  • Walk all elements in a subtree in document order.
  • Collect nodes that pass a custom acceptNode filter.
  • Process DOM nodes one at a time without building a full NodeList first.
  • Traverse mixed content when paired with whatToShow flags.
  • Debug iterator state via referenceNode after each step.

🔧 How It Works

1

Create iterator

createNodeIterator sets root, whatToShow, and filter for the walk.

Create
2

Call nextNode()

Browser finds the next node matching whatToShow and filter in document order.

Step
3

Return Node

Returns that node and advances referenceNode. Returns null when the set is exhausted.

Result
4

Repeat or stop

Keep calling nextNode() in a loop until null, or stop when you have what you need.

📝 Notes

  • MDN: Baseline Widely available (since July 2015) — no Deprecated / Experimental / Non-standard banner.
  • First nextNode() returns the first node, not the second.
  • null means the walk is finished—do not treat it as a valid node.
  • Pair with whatToShow and filter for precise walks.
  • Do not call deprecated detach() before walking.
  • Related learning: referenceNode, root, childNodes.

Universal Browser Support

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

Baseline · Widely available

NodeIterator.nextNode()

Returns the next node in document order and advances the iterator—or null when done.

Universal Widely available
Google Chrome Full support · Desktop & Mobile
Full support
Mozilla Firefox Full support · Desktop & Mobile
Full support
Apple Safari Full support · macOS & iOS
Full support
Microsoft Edge Full support · Chromium
Full support
Opera Full support · Modern versions
Full support
Internet Explorer Supported on NodeIterator (legacy DOM)
Legacy OK
NodeIterator.nextNode() Excellent

Bottom line: Call nextNode() in a while loop to walk a DOM subtree created with createNodeIterator.

Conclusion

NodeIterator.nextNode() is the main way to walk a DOM subtree forward. The first call returns the first node; later calls advance until null. Combine it with whatToShow and filter for precise traversal.

Continue with previousNode(), referenceNode, filter, or the JavaScript hub.

💡 Best Practices

✅ Do

  • Use while ((n = it.nextNode())) for full walks
  • Check for null before using the returned node
  • Scope iterators to the smallest useful root
  • Combine whatToShow with a custom filter when needed
  • Read referenceNode when debugging iterator position

❌ Don’t

  • Assume the first call skips the first node (it does not)
  • Ignore null and keep calling without checking
  • Call deprecated detach() before walking
  • Use NodeIterator when querySelectorAll is enough
  • Mutate the DOM recklessly mid-walk on live subtrees

Key Takeaways

Knowledge Unlocked

Five things to remember about NodeIterator.nextNode()

Forward walk, one node at a time.

5
Core concepts
⚙️02

First call

first node

Rule
🚀03

Advances

iterator

State
📄04

Done?

null

Stop
🎯05

Baseline

since Jul 2015

Status

❓ Frequently Asked Questions

The next node in document order within the iterator's subtree, or null when no nodes remain. The first call returns the first node in the set.
No. MDN marks NodeIterator.nextNode() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
When you have reached the end of the walk—there are no more nodes to return in the iterator's set (after whatToShow and filter screening).
Yes. Each successful call advances the iterator and updates referenceNode (and pointerBeforeReferenceNode) to reflect the new position.
nextNode() moves forward in document order; previousNode() moves backward. Both return a Node or null at the ends of the walk.
Old specs said detach() could invalidate the iterator and cause INVALID_STATE_ERR. Modern browsers treat detach() as a no-op and usually do not throw—still avoid detach() in new code.
Did you know?

MDN’s example assigns currentNode = nodeIterator.nextNode() on the first line. That is the standard idiom—the first call already gives you the first node in the set, not an empty step.

Explore previousNode()

Learn the backward walk method that pairs with nextNode().

previousNode() method →

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.

5 people found this page helpful