Skip to content

Instantly share code, notes, and snippets.

@ginader
Forked from Haprog/deepQuerySelectorAll.js
Created March 31, 2023 12:51
Show Gist options
  • Save ginader/e4ae877c3ba4227e53c08b0777e51e19 to your computer and use it in GitHub Desktop.
Save ginader/e4ae877c3ba4227e53c08b0777e51e19 to your computer and use it in GitHub Desktop.
A version of querySelectorAll() that also recursively looks into all shadow roots
/**
* 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