Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymer Access Element Inside of Nested Template by Id

Tags:

nested

polymer

Polymer provides access to elements by id via this.$['foo']. However, I find that I am unable to access elements by id that are in nested templates.

<template>
  <div id="foo"></div>
  <template>
    <div id="bar"></div>
  </template>
</template>

In this situation this.$.foo works but this.$.bar does not. Are you able to access elements inside of a nested template by id and if so how?

In my code I'm using a conditional template to include some html if a attribute is true. I was providing this functionality in javascript by editing the html but think that conditional templates more clearly show what is going on and I would prefer to use this method.

like image 826
RogerSmith Avatar asked Jul 03 '14 18:07

RogerSmith


1 Answers

Using this.$.<id> syntax does work with inner templates. The problem in your example is that the inner <template> is inert, and it isn't rendered. I've rewritten your example so that the inner <template> is rendered, and you can see that the this.$.<id> syntax works for both the outer and inner <template>s:

<polymer-element name="my-element">
  <template>
    <div id="foo">
      <p>Old foo</p>
      <template if="{{showBar}}">
        <div id="bar">
          <p>Old bar</p>
        </div>
      </template>
    </div>
    <button on-tap="{{changeContent}}">Change Content</button>
  </template>
  <script>
    Polymer({
      showBar: true,
      changeContent: function() {
        this.$.foo.querySelector('p').textContent = 'New foo';
        this.$.bar.querySelector('p').textContent = 'New bar';
      }
    });
  </script>
</polymer-element>

Pressing the "Change Content" button finds the #foo and #bar <div>s and updates the text of the contained <p>s.

You can try out the answer at http://jsbin.com/roceta/edit.

like image 195
Shailen Tuli Avatar answered Oct 09 '22 23:10

Shailen Tuli