Search code examples
javascriptpolymershadow-dom

Query element in nested shadow root


Scenerio: In my application I have nested shadow-roots, and I want to get an element in the inner shadow-root from outer shadow-root.

What I actually mean is that consider this scenerio.

<Component 1 id="headerComponent">
#shadow-root // outer shadow-root.
  <div class="header"></div> // element in outer shadow-root.
  #shadow-root // inner shadow-root.
    <Component 2 id="titleComponent"> // We have component 2 inside the shadow root of component 1.
       <input class="titleInput"> // element inside inner shadow-root.

Now, If I am in Component 1.js and want to Query any element in Component 1.js, I will write this block of code this.shadowRoot.querySelector('.header');, and it works well.

But, If I am in Component 1.js and want to Query an element(here it is <input> with class titleInput) in Component 2.js, How can I do it?

Trying the similar statement like this.shadowRoot.querySelector('.titleInput'); doesn't seems to work and returns null.


Solution

  • I managed to solve the problem. Here is the snippet of js that will do the magic.

    this.$.titleComponent.shadowRoot.querySelector('.input-wrap');
    

    For those who are not familier with polymer architecture.

    Here, As I am in Component 1. So, this refers to component 1(Component 1 class methods, properties and this.$ is used to select elements inside Component 1 class template having the id followed by this.$.elementID), this.$.titleComponent selects titleComponent and this statement selects the element shadowRoot.querySelector('.input-wrap').