Created
June 24, 2021 17:09
-
-
Save fijiwebdesign/d2fcf9ecefbda9033ea05f11577b9c47 to your computer and use it in GitHub Desktop.
Query selector that selects all elements including those in ShadowDOM
This file contains hidden or 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
document.body.querySelectorAll('.button') // only buttons not in shadow dom | |
$query('.button') // all .button including those in shadow dom |
This file contains hidden or 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
$query = (query) => _query(query, document.body) | |
_childNodesDeep = parent => { | |
return [...parent.childNodes].map(child => [child, ..._childNodesDeep(child)]).flat() | |
} | |
_shadowsDeep = parent => { | |
return _childNodesDeep(parent) | |
.map(c => c.shadowRoot) | |
.filter(s => s) | |
.map(s => [s, ..._shadowsDeep(s)]) | |
.flat() | |
} | |
_query = (query, parent, matches = []) => { | |
if (!parent) return | |
matches = parent.querySelectorAll(query) | |
shadows = _shadowsDeep(parent) | |
matches = [...matches, ...shadows.map(s => Array.from(s.querySelectorAll(query)))].filter(m => m.length).flat() | |
return matches | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment