Search code examples
javascriptshadow-dom

how to querySelect from shadow root that was created with closed mode


I have a shadow root that was created with mode: closed

<session-expiration-popup>
  #shadow root (closed)
  <div class="custom-element-root">
    something
  </div>
</session-expiration-popup>

Is there any way to querySelect something from this shadow root?

I tried

const el = document.querySelector('session-expiration-popup')
el.shadowRoot.querySelector(".custom-element-root");

however, it is not working cause shawRoot param is null for mode: close

Also, I tried to el.attachShadow({ mode: "open" }) but it's also the wrong way that leads to the exception (shadow root exist for el element).

Do you have any other ideas?


Solution

  • It's not possible. It's the intended behaviour and the purpose of a closed Shadow DOM.

    The only workaround is to overload the attachShadow() method and then create an open Shadow DOM instead when the method is invoked.

    Example in this post.