Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Find all nodes used on the page, deep within v0 and v1 shadow DOM.
/**
* @author ebidel@ (Eric Bidelman)
* License Apache-2.0
*/
/**
* Convenience method finding all the DOM child nodes of a parent,
* includibg those within shadow roots. By default, all children
* under `<body>` will be returned. The parent node can be overridden
* by passing the `selector` param.
*
* @param {string=} selector A parent node.
* @return {!Array<HTMLElement>} An array of child nodes for `selector`.
*/
function deepFindAllElements(selector = 'body') {
// If the browser doesn't support Shadow DOM, just get all children nodes.
let nodes = document.querySelectorAll(`${selector} *`);
try {
// Shadow DOM v0: /deep/ matches nodes within shadow roots.
nodes = document.querySelectorAll(`${selector} /deep/ *`);
} catch(e) { /* noop */ }
let v1Nodes = [];
try {
// Shadow DOM v1: >>> matches nodes within open shadow roots.
v1Nodes = document.querySelectorAll(`${selector} >>> *`);
} catch(e) { /* noop */ }
// Remove duplicates.
const unique = new Set([...nodes].concat([...v1Nodes]));
return [...unique];
}
deepFindAllElements();
// deepFindAllElements('html');
// deepFindAllElements('#specific_element');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.