Skip to content

Instantly share code, notes, and snippets.

@Danny-Engelman
Created March 23, 2021 11:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Danny-Engelman/e4ae579ad5b53db0d6ab1a4dfea6fdcb to your computer and use it in GitHub Desktop.
Save Danny-Engelman/e4ae579ad5b53db0d6ab1a4dfea6fdcb to your computer and use it in GitHub Desktop.
findElements with TreeWalker API
// The native TreeWalker API has been around for ages, IE9 was the last Browser to implement it ... in 2011
function log() {
console.log(`%c TreeWalker `, `background:purple;color:yellow`, ...arguments);
}
// find element takes a function definition, the output must be Truthy or Falsy
function findElements(
acceptFunc = (x) => customElements.get(x.localName) || false
) {
log("start");
console.time("TreeWalker");
let elements = [];
function dive(root = document.body) {
let iterator;
iterator = document.createNodeIterator(
root,
NodeFilter.SHOW_ELEMENT,
(node) =>
acceptFunc(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT
);
let node;
while ((node = iterator.nextNode())) {
if (node.shadowRoot) {
log("dive into shadowRoot at", node.localName, node.id);
[...node.shadowRoot.children].forEach((shadowNode) => dive(shadowNode));
}
elements.push(node);
}
}
dive();
log(elements.length, `elements found`);
console.timeEnd("TreeWalker", `%c end`, `background:purple`);
return elements;
}
console.clear();
findElements((x) => true);
findElements();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment