Example 1 — Iterate Matching Nodes
Find all h2 elements under a context node and walk them with iterateNext().
const root = document.createElement("div");
root.innerHTML = "<h2>Alpha</h2><h2>Beta</h2>";
const result = document.evaluate(
".//h2",
root,
null,
XPathResult.ORDERED_NODE_ITERATOR_TYPE,
null
);
const texts = [];
let node = result.iterateNext();
while (node) {
texts.push(node.textContent);
node = result.iterateNext();
}
console.log(texts.join(", ")); // Alpha, Beta How It Works
- Build a tiny tree. Two headings give a predictable XPath target.
- Evaluate.
".//h2"searches descendants ofroot. - Use an iterator.
ORDERED_NODE_ITERATOR_TYPEkeeps document order. - Walk results. Call
iterateNext()until it returnsnull.

