JavaScript NodeIterator previousNode() Method

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

What You’ll Learn

The previousNode() method of a NodeIterator returns the previous node in document order and moves the iterator backward. Learn backtracking after nextNode(), null at the first node, and how it updates referenceNode—with five examples and try-it labs.

01

Kind

Instance method

02

Returns

Node or null

03

Params

None

04

Direction

Backward

05

Pair

nextNode()

06

Status

Baseline widely

Introduction

A NodeIterator usually walks forward with nextNode(). When you need to move back one step, call previousNode(). It returns the node before the current position and shifts the iterator backward in document order.

MDN’s classic pattern: call nextNode() once, then previousNode()—you land on the same node again because you backtracked. At the very start of the set, previousNode() returns null.

💡
Beginner tip

Think of nextNode() and previousNode() as forward and backward buttons. Most loops only need nextNode(), but backtracking helps when you overshoot or need reversible traversal.

Understanding the previousNode() Method

An instance method on NodeIterator that returns the previous node in the iterator’s set and moves the position backward.

  • Returns — a Node, or null at the first node.
  • Parameters — none.
  • Direction — backward in document order.
  • 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.previousNode()

Parameters

None.

Return value

A Node representing the previous node in the set, or null if the current node is the first one.

Typical pattern (MDN idea)

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

const forward = nodeIterator.nextNode();
const back = nodeIterator.previousNode();
console.log(forward === back); // true — backtracked to same node

⚡ Quick Reference

GoalCode / note
Previous nodeiterator.previousNode()
BacktrackCall after nextNode()
At first node?Returns null
Forward pairnextNode()
ParametersNone
MDN statusBaseline Widely available (since July 2015)

🔍 At a Glance

Four facts to remember about NodeIterator.previousNode().

Returns
Node|null

Prev or start

Params
none

No arguments

Direction
backward

Document order

Baseline
widely

Since Jul 2015

Examples Gallery

Examples follow MDN NodeIterator.previousNode. Labs show backtracking, null at the start, and paired forward/backward walks.

📚 Getting Started

Backtrack and boundary behavior.

Example 1 — Backtrack After nextNode() (MDN Idea)

Move forward one step, then return to the same node.

JavaScript
const it = document.createNodeIterator(
  document.getElementById("box"),
  NodeFilter.SHOW_ELEMENT,
  { acceptNode: () => NodeFilter.FILTER_ACCEPT },
);

const forward = it.nextNode();
const back = it.previousNode();
console.log(forward === back); // true
Try It Yourself

How It Works

MDN: after one nextNode(), previousNode() returns the same node because the iterator moved back one position.

Example 2 — null at the First Node

Before any forward walk, there is no previous node.

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

console.log(it.previousNode()); // null — already at first position
Try It Yourself

How It Works

MDN: previousNode() returns null when the current node is the first node in the set.

📈 Practical Patterns

Walk forward, then retrace your steps.

Example 3 — Walk Forward, Then Backward

Collect tag names going forward, then backward until null.

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

const forward = [];
let node;
while ((node = it.nextNode())) forward.push(node.nodeName);

const backward = [];
while ((node = it.previousNode())) backward.push(node.nodeName);

console.log(forward);   // ["DIV", "SPAN", "SPAN"]
console.log(backward);  // ["SPAN", "SPAN", "DIV"]
Try It Yourself

How It Works

After the forward walk ends at the last node, repeated previousNode() visits nodes in reverse order until the start.

Example 4 — previousNode() Updates referenceNode

Step forward twice, then back once—anchor moves with each call.

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

it.nextNode();
const second = it.nextNode();
it.previousNode();
console.log(it.referenceNode === second); // false — moved back one step
Try It Yourself

How It Works

After backtracking, referenceNode points at the node before second. See referenceNode for the full picture.

Example 5 — Backtrack Through Filtered Nodes

Only accepted nodes appear when walking backward too.

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

it.nextNode(); // first .pick
it.nextNode(); // second .pick
const back = it.previousNode();
console.log(back.textContent.trim()); // "A"
Try It Yourself

How It Works

previousNode() skips rejected nodes the same way nextNode() does.

🚀 Common Use Cases

  • Undo one forward step after overshooting with nextNode().
  • Implement reversible tree walks without rebuilding state.
  • Debug iterator position by stepping forward and backward.
  • Walk to the end forward, then process nodes in reverse with previousNode().
  • Pair with referenceNode when teaching iterator anchor behavior.

🔧 How It Works

1

Iterator position

referenceNode and pointerBeforeReferenceNode track where you are in the subtree.

State
2

Call previousNode()

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

Step
3

Return Node

Returns that node and moves backward. Returns null at the first node.

Result
4

Pair with nextNode()

Use both methods for bidirectional walks inside the iterator's fixed root subtree.

📝 Notes

  • MDN: Baseline Widely available (since July 2015) — no Deprecated / Experimental / Non-standard banner.
  • null at the start means you cannot go further backward.
  • Most everyday loops only need nextNode(); use previousNode() when you need backtracking.
  • Respects the same whatToShow and filter rules as forward walks.
  • Do not call deprecated detach() before walking.
  • Related learning: nextNode(), referenceNode, pointerBeforeReferenceNode.

Universal Browser Support

NodeIterator.previousNode() 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.previousNode()

Returns the previous node in document order and moves the iterator backward—or null at the first node.

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.previousNode() Excellent

Bottom line: Call previousNode() to backtrack after nextNode(), or walk backward from the end of a subtree.

Conclusion

NodeIterator.previousNode() moves the iterator backward in document order. Use it to backtrack after nextNode(), or to walk from the end toward the start. It returns null when you are already at the first node.

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

💡 Best Practices

✅ Do

  • Use previousNode() to undo one forward step
  • Check for null when walking backward from the start
  • Pair with nextNode() for reversible walks
  • Read referenceNode when debugging position
  • Walk to the end with nextNode() before a backward pass

❌ Don’t

  • Expect a node when already at the first position
  • Confuse backward iterator steps with DOM node removal
  • Call deprecated detach() before walking
  • Use NodeIterator when a simple array reverse would suffice
  • Mutate the DOM heavily mid-walk without understanding live updates

Key Takeaways

Knowledge Unlocked

Five things to remember about NodeIterator.previousNode()

Backward walk, one node at a time.

5
Core concepts
⚙️02

Direction

backward

Rule
🚀03

Pair

nextNode()

Walk
📄04

Start?

null

Stop
🎯05

Baseline

since Jul 2015

Status

❓ Frequently Asked Questions

The previous node in document order within the iterator's subtree, or null when the current position is already at the first node in the set.
No. MDN marks NodeIterator.previousNode() as Baseline Widely available (since July 2015). It is not Deprecated, Experimental, or Non-standard.
When the iterator is at the first node in the set—there is no earlier node to return.
previousNode() moves backward in document order; nextNode() moves forward. Both return a Node or null at the ends of the walk.
Yes. Each successful call moves the iterator backward and updates referenceNode (and pointerBeforeReferenceNode).
Yes. MDN's example calls nextNode() then previousNode() to return to the same node—useful for reversible walks.
Did you know?

MDN’s sample calls nextNode() then previousNode() and gets the same node back. That one-step backtrack is the quickest way to see how iterator position moves.

Explore nextNode()

Pair backward steps with the forward walk method.

nextNode() 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