Created
March 23, 2021 11:26
-
-
Save Danny-Engelman/e4ae579ad5b53db0d6ab1a4dfea6fdcb to your computer and use it in GitHub Desktop.
findElements with TreeWalker API
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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