DOM Tree walking


Example

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.