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. |