Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@mmocny
Created October 6, 2022 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mmocny/d7015a0e85e045307cc6901da7073fec to your computer and use it in GitHub Desktop.
Save mmocny/d7015a0e85e045307cc6901da7073fec to your computer and use it in GitHub Desktop.
shadowQuerySelectorAll. Like querySelectorAll, but which works across shadowRoots
// Inspiration: https://www.abeautifulsite.net/posts/querying-through-shadow-roots/
/*
* Acts like querySelectorAll, except you can pass a list of selectors...
* Each selector is evaluated within the shadowRoot of the previous NodeList
*/
function* shadowQuerySelectorsAll(selectors, rootNode = document, depth = 0) {
const nodes = rootNode?.querySelectorAll(selectors[depth]);
if (depth >= selectors.length - 1) {
yield* nodes;
} else {
for (let node of nodes) {
yield* shadowQuerySelectorsAll(selectors, node?.shadowRoot, depth + 1);
}
}
}
/*
* As above, you can use a single string separated by `>>>`
*/
function* shadowQuerySelectorAll(selector, rootNode = document) {
const selectors = String(selector).split('>>>');
yield* shadowQuerySelectorsAll(selectors, rootNode);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment