Skip to content

Instantly share code, notes, and snippets.

@Sphinxxxx
Last active May 19, 2022 17:22
Show Gist options
  • Save Sphinxxxx/ed372d176c5c2c1fd9ea1d8d6801989b to your computer and use it in GitHub Desktop.
Save Sphinxxxx/ed372d176c5c2c1fd9ea1d8d6801989b to your computer and use it in GitHub Desktop.
DOM node tree walker

A general-purpose DOM tree walker based on https://stackoverflow.com/questions/10730309/find-all-text-nodes-in-html-page (Phrogz' answer and its comments).

The textNodesUnder() function would then look like this:

function textNodesUnder(el) {
    return walkNodeTree(el, {
        inspect: n => !['STYLE', 'SCRIPT'].includes(n.nodeName),
        collect: n => (n.nodeType === Node.TEXT_NODE),
        //callback: n => console.log(n.nodeName, n),
    });
}
//https://stackoverflow.com/questions/10730309/find-all-text-nodes-in-html-page
function walkNodeTree(root, options) {
options = options || {};
const inspect = options.inspect || (n => true),
collect = options.collect || (n => true);
const walker = document.createTreeWalker(
root,
NodeFilter.SHOW_ALL,
{
acceptNode: function(node) {
if(!inspect(node)) { return NodeFilter.FILTER_REJECT; }
if(!collect(node)) { return NodeFilter.FILTER_SKIP; }
return NodeFilter.FILTER_ACCEPT;
}
}
);
const nodes = []; let n;
while(n = walker.nextNode()) {
options.callback && options.callback(n);
nodes.push(n);
}
return nodes;
}
@netizen-ais
Copy link

It seems you're using constants, and that's good for clarity and legibility, but you forgot one:
Change n.nodeType === 3 to n.nodeType === Node.TEXT_NODE

@Sphinxxxx
Copy link
Author

Sphinxxxx commented Aug 9, 2021

@netizen-ais Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment