Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing all inner elements in Polymer?

I have:

<k-myelement>
    <k-anotherelement></k-anotherelement>
</k-myelement>

When I define the template like this:

<polymer-element name="k-myelement">
    <template>
        <content select="k-anotherelement" id="anotherelement"></content>
    </template>
</polymere-element>

I can access the inner element with this.$['anotherelement']

But with this approach I have to predefine, which inner elements can be used.

What I want is a template technique, that allows me to access all the inner elements.

like image 842
K.. Avatar asked Mar 06 '14 12:03

K..


1 Answers

<content> (insertion points) are for rendering elements in the light DOM at specific locations in the Shadow DOM. Using <content select="k-anotherelement"></content> says "render any <k-anotherelement> elements here. If you want all light DOM nodes to be invited into the rendering party, simply use <content></<content>.

The other issues with your snippet:

  • The name of the element needs to be defined on <polymer-element>, not as <template name="k-myelement">

  • To get the list of nodes that pass through a <content>, use content.getDistributedNodes(). You may also want to consider if you even need <content>. Light DOM children nodes can be access with .children and the other accessors. From the Polymer docs:

    For a <content>, you can iterate through content.getDistributedNodes() to get the list of nodes distributed at the insertion point.

    In Polymer, the best place to call this method is in the attached() callback so you’re guaranteed that the element is in the DOM tree.

    Also remember that you can access the light DOM as the element’s normal children (i.e. this.children, or other accessors). The difference with this approach is that it’s the entire set of potentially distributed nodes; not those actually distributed.

like image 73
ebidel Avatar answered Oct 24 '22 10:10

ebidel