A NodeIterator walks the nodes under a root in document order. You create one with document.createNodeIterator(root, whatToShow).
Call nextNode() to move forward and previousNode() to move back. Filters such as NodeFilter.SHOW_ELEMENT limit which nodes appear. Prefer a simple loop with querySelectorAll when you only need elements.
This page teaches what NodeIterator is. Method and property guides live under this section.
Create with document.createNodeIterator.
There is no public new NodeIterator() in normal page scripts. Always start from the document method.
Syntax
JavaScript Syntax
Create and walk an iterator:
JavaScript
const iterator = document.createNodeIterator(
root,
NodeFilter.SHOW_ELEMENT
);
let node = iterator.nextNode();
while (node) {
console.log(node.nodeName);
node = iterator.nextNode();
}
Reference
Core Ideas
Ideas every NodeIterator tutorial builds on:
Idea
Example
Remember
Create
document.createNodeIterator
Factory on document
Forward
iterator.nextNode()
Next match or null
Back
iterator.previousNode()
Previous match or null
Filter
NodeFilter.SHOW_ELEMENT
Limit node kinds
root
iterator.root
Subtree being walked
detach
iterator.detach()
Legacy no-op in modern browsers
Code
JavaScript Examples
Three short programs that show how NodeIterator works.