How do I select the .child
element using script?
To target an element in the Shadow DOM, you need to utilize the shadowRoot
property on the specific element.
var parent = document.querySelector( '#parent' )
var child = parent.shadowRoot.querySelector( '#child' )
child.classList.add( 'reached' )
Note: Make sure the Shadow DOM has been created in 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: The use of ::slotted
is only necessary when elements from the light DOM are exposed with <slot>
.
Are there alternatives to the /deep selector?
In short, no. As the main purpose of the Shadow DOM is to isolate it from the main page, the /deep
was considered somewhat controversial.
A very recent proposal, involving ::part
and ::theme
pseudo-elements may offer some level of control, but implementation might take some time.
Until then, a common workaround is to make use of CSS custom properties.
It's important to note that both solutions must be implemented by the Web Component designer and cannot be easily overridden.