Example 1 — Walk Element Nodes
Create an iterator over elements under a root and list their tags.
const root = document.createElement("div");
root.innerHTML = "<span>A</span><b>B</b>";
const it = document.createNodeIterator(root, NodeFilter.SHOW_ELEMENT);
const names = [];
let node;
while ((node = it.nextNode())) {
names.push(node.nodeName.toLowerCase());
}
console.log(names); // ["div", "span", "b"] How It Works
- Build a small tree. A root
divwith two children. - Create the iterator.
SHOW_ELEMENTskips text nodes. - Loop nextNode. Each call advances to the next matching node.
- Stop on null. When the walk finishes,
nextNode()returnsnull.

