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);

2 Answers 2

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>

2
  • Not able to understand your code. How can get that content innerHTML?
    – sarann
    Feb 25, 2022 at 17:55
  • Yes, that console.warn shows your matched <content> Feb 25, 2022 at 19:01
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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.