Last active
August 9, 2021 20:05
-
-
Save ebidel/1b418134837a7dde7d76ed36288c1d16 to your computer and use it in GitHub Desktop.
Finds all elements on the page, including those within shadow dom.
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
/** | |
* @author ebidel@ (Eric Bidelman) | |
* License Apache-2.0 | |
*/ | |
/** | |
* Finds all elements on the page, inclusive of those within shadow roots. | |
* @param {string=} selector Simple selector to filter the elements by. e.g. 'a', 'div.main' | |
* @return {!Array<string>} List of anchor hrefs. | |
*/ | |
function collectAllElementsDeep(selector = null) { | |
const allElements = []; | |
const findAllElements = function(nodes) { | |
for (let i = 0, el; el = nodes[i]; ++i) { | |
allElements.push(el); | |
// If the element has a shadow root, dig deeper. | |
if (el.shadowRoot) { | |
findAllElements(el.shadowRoot.querySelectorAll('*')); | |
} | |
} | |
}; | |
findAllElements(document.querySelectorAll('*')); | |
return selector ? allElements.filter(el => el.matches(selector)) : allElements; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment