Skip to content Skip to sidebar Skip to footer

How Do I Traverse Elements Within A Shadow Dom

I have div id=outer #shadowRoot div id=inner button In the click handler of the button, I want to reference the div 'inner'. In a non shadowDom world, this would be docu

Solution 1:

You could use the absolute path: use shadowRoot to get the Shadow DOM content.

document.querySelector( 'div#outer' ).shadowRoot.querySelector( 'div#inner' )

Or the relative path: use getRootNode() to get the Shadow DOM root

event.target.getRootNode().querySelector( 'div#inner' )

Example:

outer.attachShadow( { mode: 'open' } )
    .innerHTML = `
        <div id=inner></div>
        <button>clicked</button>
    `
    
outer.shadowRoot.querySelector( 'button' ).onclick = ev =>
  ev.target.getRootNode().querySelector( 'div#inner' ).innerHTML = 'clicked'
<divid=outer></div>

Post a Comment for "How Do I Traverse Elements Within A Shadow Dom"