Skip to content Skip to sidebar Skip to footer

Accessing A Div Inside Of A Polymer Element Template

I'm trying to use core-animation on a div, to animate its position. To do that, i have to select it with document.getElementById(). The problem is, i have a rather complex structur

Solution 1:

If your element is inside a template, then it does not belong to the DOM but the shadow DOM. As a complement, in the Web Components site there is an article on the topic and Rob Dodson wrote a detailed article about the basics of shadow DOM.

Edit : Polymer 1.0 introduced a specific concept, Shady DOM...

I admit the relationship between a polymer element, multiple templates and shadow DOM is not really obvious to me. At first glance, a shadow DOM is associated to a template. A few explanations are available in that other article by Rob Dodson about templates repetition. It seems with repetitions things become subtle: here you have a single shadow DOM and the ID becomes pointless. The worse is that I guess you have nested shadow DOMs because of the nested templates. What is not clear at all to me is here: what about visibility in such a context ?

Edit : more informations about visibility are available in that later exchange...

Edit : template repetition syntax has evolved in Polymer 1.0

As a conclusion (in my understanding), because of the template repetition you could have multiple identical IDs even inside the repeated template shadow DOM. The valid strategy would be to use a class for selection instead of an ID.

Javascript is associated to a Polymer element with a method call. To select via Javascript in the shadow DOM, you should use the querySelector. The solution you suggested with document.getElementById() is valid for the DOM. The point is about nested templates. You have a hint with another exchange on the topic. A solution is suggested with this.shadowRoot.querySelectorAll(...) but an issue in the Polymer project covers the point: this could work but probably not a good practice. The details in the Polymer documentation about node finding are here: in that article there is a sample looking like your problem.

According to the Polymer doc, when you call the Polymer element method, assuming you want the selection in the ready event and a container ID assigned in your nesting template, this should look something like this:

<polymer-elementname="my-element"...><template...><divid="container"><template...>
        ...
        <divclass="el"></div>
        ...
      </template></div></template><script>Polymer('my-element', {
  ready: function() {
    this.$.container.querySelector('.el');
  }
});
  </script></polymer-element>

Post a Comment for "Accessing A Div Inside Of A Polymer Element Template"