DOM Iterating over nodes


Example

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

Given a document like this one:

<html>
<body>
  <section class="main">
    <ul>
      <li>List Item</li>
      <li>List Item</li>
      <li>List Item</li>
      <li>List Item</li>
    </ul>
  </section>
</body>
</html>

One could imagine an iterator to get the <li> 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 from the document.createNodeIterator() documentation on the Mozilla Developer Network, licensed under CC-by-SA 2.5.

This will log something like:

<li>List Item</li>
<li>List Item</li>
<li>List Item</li>
<li>List Item</li>

Note that this is similar to the TreeWalker iterface, but provides only nextNode() and previousNode() functionality.