Skip to content

Instantly share code, notes, and snippets.

@fijiwebdesign
Created June 24, 2021 17:09
Show Gist options
  • Save fijiwebdesign/d2fcf9ecefbda9033ea05f11577b9c47 to your computer and use it in GitHub Desktop.
Save fijiwebdesign/d2fcf9ecefbda9033ea05f11577b9c47 to your computer and use it in GitHub Desktop.
Query selector that selects all elements including those in ShadowDOM
document.body.querySelectorAll('.button') // only buttons not in shadow dom
$query('.button') // all .button including those in shadow dom
$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