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)
Parameter | Details |
---|---|
root | The 'root' node who's subtree is to be traveresed |
whatToShow | Optional, unsigned long designating what types of nodes to show. See NodeFilter for more information. |
filter | Optional, An object with an acceptNode method to determine whether a node, after passing the whatToShow check should be considered |
entityReferenceExpansion | Obsolete and optional, Is a Boolean flag indicating if when discarding an EntityReference its whole sub-tree must be discarded at the same time. |
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.