-
-
Save ginader/e4ae877c3ba4227e53c08b0777e51e19 to your computer and use it in GitHub Desktop.
A version of querySelectorAll() that also recursively looks into all shadow roots
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
/** | |
* A version of querySelectorAll() that also recursively looks into all shadow roots. | |
* @param selector Selector | |
* @param root (Optional) Scope of the query (Element or Document). Defaults to the document. | |
* @returns | |
*/ | |
function deepQuerySelectorAll(selector, root) { | |
root = root || document; | |
const results = Array.from(root.querySelectorAll(selector)); | |
const pushNestedResults = function (root) { | |
deepQuerySelectorAll(selector, root) | |
.forEach(elem => { | |
if (!results.includes(elem)) { | |
results.push(elem); | |
} | |
}); | |
}; | |
if (root.shadowRoot) { | |
pushNestedResults(root.shadowRoot); | |
} | |
for (const elem of root.querySelectorAll('*')) { | |
if (elem.shadowRoot) { | |
pushNestedResults(elem.shadowRoot); | |
} | |
} | |
return results; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment