Created
October 6, 2022 16:43
-
-
Save mmocny/d7015a0e85e045307cc6901da7073fec to your computer and use it in GitHub Desktop.
shadowQuerySelectorAll. Like querySelectorAll, but which works across shadowRoots
This file contains 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
// 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