Traversal

Other topics

Tree walking

TreeWalker is a generator-like interface that makes recursively filtering nodes in a DOM tree easy and efficient.

The following code concatenates the value of all Text nodes in the page, and prints the result.

let parentNode = document.body;
let treeWalker = document.createTreeWalker(parentNode, NodeFilter.SHOW_TEXT);

let text = "";
while (treeWalker.nextNode())
    text += treeWalker.currentNode.nodeValue;

console.log(text); // all text in the page, concatenated

The .createTreeWalker function has a signature of

createTreeWalker(root, whatToShow, filter, entityReferenceExpansion)
ParameterDetails
rootThe 'root' node who's subtree is to be traveresed
whatToShowOptional, unsigned long designating what types of nodes to show. See NodeFilter for more information.
filterOptional, An object with an acceptNode method to determine whether a node, after passing the whatToShow check should be considered
entityReferenceExpansionObsolete and optional, Is a Boolean flag indicating if when discarding an EntityReference its whole sub-tree must be discarded at the same time.

Iterating over nodes

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.

Contributors

Topic Id: 5261

Example Ids: 5505,20634

This site is not affiliated with any of the contributors.