How to querySelector elements of an element's

2020-02-12 04:48发布

I have my element :

<dom-module id="x-el">
  <p class="special-paragraph">first paragraph</p>
  <content></content>
</dom-module>

and I use it like

<x-el>
  <p class="special-paragraph">second paragraph</p>
</x-el>

in my imperative part:

Polymer({
  is: 'x-el',

  ready: function () {
    /* this will select all .special-paragraph in the light DOM
       e.g. 'second paragraph' */
    Polymer.dom(this).querySelectorAll('.special-paragraph');

    /* this will select all .special-paragraph in the local DOM
       e.g. 'first paragraph' */
    Polymer.dom(this.root).querySelectorAll('.special-paragraph');

    /* how can I select all .special-paragraph in both light DOM and
       local DOM ? */
  }
});

Is it possible to do that using Polymer built-in's ? Or should I use the default DOM api ?

2条回答
Ridiculous、
2楼-- · 2020-02-12 05:03

Another solution you can keep in mind is this one:

var elements = this.shadowRoot.querySelectorAll("input")
查看更多
Rolldiameter
3楼-- · 2020-02-12 05:16

Polymer does not provide a helper function or abstraction that will list nodes both from the light and local DOMs.

If you require this functionality, you can use this.querySelector(selector).

On a side note, aside from the Polymer.dom(this.root).querySelectorAll(selector) method, Polymer also provides the $$ utility function which helps in accessing members of an element's local DOM. This function is used as follows:

<dom-module id="my-element">
  <template>
    <p class="special-paragraph">...</p>
    <content></content>
  </template>
</dom-module>

<script>
  Polymer({
    is: 'my-element',
    ready: {
      this.$$('.special-paragraph'); // Will return the <p> in the local DOM
    }
  });
</script>

Note that, unlike querySelectorAll, the $$ function only returns one element: the first element in the local DOM which matches the selector.

查看更多
登录 后发表回答