DOM

Traversal

Tree walking

Iterating over nodes

The NodeIterator interface provides methods for iterating over nodes in a DOM tree.

Given a document like this one:

  • List Item
  • List Item
  • List Item
  • List Item
One could imagine an iterator to get the `
  • ` elements: let root = document.body; let whatToShow = NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT; let filter = (node) => node.nodeName.toLowerCase() === 'li' ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT; let iterator = document.createNodeIterator(root, whatToShow, filter); var node; while (node = iterator.nextNode()) { console.log(node); } *Example adapted from the example provided by the [Mozilla Contributors](https://developer.mozilla.org/en-US/docs/Web/API/Document/createNodeIterator$history) from the [`document.createNodeIterator()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createNodeIterator) documentation on the Mozilla Developer Network, licensed under [CC-by-SA 2.5](https://creativecommons.org/licenses/by-sa/2.5/).* This will log something like:
  • List Item
  • List Item
  • List Item
  • List Item
  • Note that this is similar to the [TreeWalker](https://stackoverflow.com/documentation/dom/drafts/74478) iterface, but provides only `nextNode()` and `previousNode()` functionality.

    This modified text is an extract of the original Stack Overflow Documentation created by the contributors and released under CC BY-SA 3.0 This website is not affiliated with Stack Overflow