Skip to content

Instantly share code, notes, and snippets.

@Haprog
Created May 5, 2021 08:36
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Haprog/848fc451c25da00b540e6d34c301e96a to your computer and use it in GitHub Desktop.
Save Haprog/848fc451c25da00b540e6d34c301e96a 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;
}
@andrescevp
Copy link

some enhaces

const DeepQuerySelectorAll = (
  selector,
  root,
  maxLevel = 3,
  current = 1,
) => {
  root = root || document;
  const results = Array.from(root.querySelectorAll(selector));
  if (current >= maxLevel) {
    return results;
  }
  const pushNestedResults = (parent) => {
    DeepQuerySelectorAll(selector, parent, maxLevel, current + 1).forEach(
      (elem) => {
        if (!results.includes(elem)) {
          results.push(elem);
        }
      },
    );
  };
  if (root.shadowRoot) {
    pushNestedResults(root.shadowRoot);
  }
  const allElements = root.getElementsByTagName("*");
  Object.values(allElements).forEach((elem) => {
    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