简体   繁体   English

嵌套影子根中的查询元素

[英]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 . Scenerio :在我的应用程序中,我嵌套了shadow-roots ,并且我想从外部shadow-root获取内部 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');现在,如果我在Component 1.js中并想查询Component 1.js中的任何元素,我将编写这段代码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?但是,如果我在Component 1.js中并想在 Component Component 2.js中查询一个元素(这里是<input>和 class titleInput ),我该怎么做?

Trying the similar statement like this.shadowRoot.querySelector('.titleInput');尝试类似的语句this.shadowRoot.querySelector('.titleInput'); doesn't seems to work and returns null .似乎不起作用并返回null

I managed to solve the problem.我设法解决了这个问题。 Here is the snippet of js that will do the magic.这是可以发挥作用的 js 片段。

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

For those who are not familier with polymer architecture.对于那些不熟悉 polymer 架构的人。

Here, As I am in Component 1 .在这里,就像我在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') .因此, this是指组件 1(组件 1 class 方法、属性和 this.$ 用于select组件 1 ZA2F2ED4F8E18F16EFCF42Z 元素内的元素 class 模板具有 id 和 this.$title 组件标题this.$.titleComponent选择元素shadowRoot.querySelector('.input-wrap')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM