0

I am trying to select a tag from shadow root but not working. So, How to select particular tag from nested shadow root elements?

#shadow-root(open)
<start>
   #shadow-root(open)
     <plural>
       #shadow-root(open)
           <main>
              #shadow-root(open)
                 <content>
                    <p>..text..</p>
                 </content>
           </main>
     </plural> 
</starts>

Typescript:

  let inside = this.shadowRoot.querySelector('content').innerHTML;
  console.log(inside);
sarann
  • 31
  • 1
  • 7

2 Answers2

0

For an unknown levels of shadowRoot you need to "Walk the DOM" and dive into shadowRoots:

<my-component>
  #shadow-root(open)
  <my-component>
    #shadow-root(open)
    <my-component>
      #shadow-root(open)
      <content>
        <p>..text..</p>
      </content>
    </my-component>
  </my-component>
</my-component>

<script>
customElements.define("my-component", class extends HTMLElement {
  constructor() {
    super().attachShadow({mode:"open"}).innerHTML = `<slot></slot>`;
  }
})

const shadowDive = (
  el,
  selector,
  match = (el, root) => {
    console.warn('match', el, root);
  },
  root = el.shadowRoot || el
) => {
  root.querySelector(selector) && match(root.querySelector(selector), root);
  [...root.querySelectorAll("*")].map(el => shadowDive(el, selector, match));
}
shadowDive(document.body, "content"); // note optional parameters
</script>
Danny '365CSI' Engelman
  • 16,526
  • 2
  • 32
  • 49
0

To select an element from a nested shadow root, you can use the querySelector().shadowRoot method in order to access each shadow root level:

// Assuming you have the parent element that contains the shadow root
const parentElement = document.querySelector('#start');

// Access the first shadow root
const firstShadowRoot = parentElement.shadowRoot;

// Access the second shadow root
const secondShadowRoot = firstShadowRoot.querySelector('plural').shadowRoot;

// Access the third shadow root
const thirdShadowRoot = secondShadowRoot.querySelector('main').shadowRoot;

// Get the paragraph inside the third shadow root
const p = thirdShadowRoot.querySelector('p');

console.log(p.textContent);

Please note: you cannot skip a shadow DOM level, so make sure you follow each one of them from the top of the DOM.

Another tip that might help:

When handling a complex DOM which envolved many nested Shadow DOMs the best way to find your element path is using the devtools: right click on the element > Copy > Copy js path (example for Chrome)

I.sh.
  • 252
  • 3
  • 13