Created
May 5, 2021 08:36
-
-
Save Haprog/848fc451c25da00b540e6d34c301e96a 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
some enhaces