DOM Iterating over nodes


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

Given a document like this one:

  <section class="main">
      <li>List Item</li>
      <li>List Item</li>
      <li>List Item</li>
      <li>List Item</li>

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 : 
let iterator = document.createNodeIterator(root, whatToShow, filter);
var node;
while (node = iterator.nextNode()) {

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.