Skip to content

Instantly share code, notes, and snippets.

@heyMP
Last active Aug 3, 2021
Embed
What would you like to do?
Recursively find elements through multiple layers of shadow dom.
/**
* Example usage:
* const hotspots = findAllDeep(this.shadowRoot.querySelector('slot'), `[slot*="hotspot"]`, 1);
*/
export const findAllDeep = (parent, selectors, depth = null) => {
let nodes = [];
let currentDepth = 1;
const recursiveSeek = _parent => {
// record the nodes
for (let child of _parent.assignedNodes({ flatten: true })) {
// if it is a legit element
if (child.querySelector) {
// save the found nodes and keep moving
const foundItems = child.querySelectorAll(selectors);
nodes = [...nodes, ...foundItems];
// now loop of each of the found see if we can sniff out more slots
if (depth && currentDepth < depth) {
for (slot of child.querySelectorAll('slot')) {
recursiveSeek(slot);
}
}
}
}
};
recursiveSeek(parent);
return nodes;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment