5

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 document.getElementById('inner'), but what is the equivalent in a shadow DOM world?

NB. This is accessing from within the custom-element. I am not trying to pierce the shadow DOM from outside.

Supersharp
  • 29,002
  • 9
  • 92
  • 134
pinoyyid
  • 21,499
  • 14
  • 64
  • 115
  • Possible duplicate of [Is it possible to access Shadow DOM elements through the parent document?](https://stackoverflow.com/questions/16633057/is-it-possible-to-access-shadow-dom-elements-through-the-parent-document) – P Varga May 05 '19 at 15:11
  • Rather than access through the parent document, I was trying to access from an event within the shadowRoot. – pinoyyid May 05 '19 at 15:42

1 Answers1

7

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'
<div id=outer></div>
Supersharp
  • 29,002
  • 9
  • 92
  • 134