How can I write the selector in the script to reach the .child
element?
To reach an element in the Shadow DOM, you should use the shadowRoot
property on the element.
var parent = document.querySelector( '#parent' )
var child = parent.shadowRoot.querySelector( '#child' )
child.classList.add( 'reached' )
Note : the Shadow DOM must have been created in the open mode.
var sh = parent.attachShadow( { mode: 'open' } )
var parent = document.querySelector( '#parent' )
var sh = parent.attachShadow( { mode: 'open' } )
sh.innerHTML = `<style>
div.reached { color: green }
</style>
<div id="child">Child</div>
`
var child = parent.shadowRoot.querySelector( '#child' )
child.classList.add( 'reached' )
<div id="parent">
</div>
Note: ::slotted
is needed only if you have elements in the light DOM revealed with <slot>
.
Is there alternative to /deep selector?
Short answer is no. Since Shadow DOM is aimed at isolating Shadom DOM from the main page, /deep
was kind of an heresy.
A very new proposal, with ::part
and ::theme
pseudo-elements could give some control back, but it's not to be implemented soon.
Until then the main workaround is to use CSS custom properties.
However the 2 solutions must be implemented by the Web Component designer and cannot be overrided otherwise.
querySelector
andquerySelectorAll
. They will save you lots of confusion and difficulty. – IntervaliaquerySelector
can not penetrate shadowDOM. Instead you need to get to the component with onequerySelector
and then use a secondquerySelector
on theshadowRoot
of the element. – Intervalia