Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Polymer : this.$[elementId] is undefined

Tags:

polymer

Here is a simple polymer element which just access an inner element using its id and this.$.[elementId], and then log it. Running, this simple code, you will be able to see that the returned element undefined. Why?

<dom-module id="custom-element">
  <template>
          <template is="dom-if" if="[[condition]]">
             <div id="main"></div>
          </template>
  </template>

  <script>
    class CustomElement extends Polymer.Element {
      static get is() { return "custom-element"; }
            static get properties() {
                return {
                   condition : Boolean
                };
            }

            ready(){
                super.ready();
                console.log(this.$.main); // logs "undefined"
            }
    }
    
    customElements.define(CustomElement.is, CustomElement);
  </script>

</dom-module>
like image 733
Yairopro Avatar asked Jan 03 '23 19:01

Yairopro


1 Answers

The Polymer this.$ only references elements from local DOM which are not added dynamicly. Thus, elements placed inside dom-if or dom-repeat templates are not added to the this.$ object.

If you wish to select a dynamic element you need to go to the dom and use something like this.shadowRoot.querySelector('#main')


Here's a solution to get rid of this problem. Add the following code in your ready():

if (this.$)
    this.$ = new Proxy(this.$, {
        get: ($, id) => $[id] || this.shadowRoot.getElementById(id),
        set: ($, id, element) => {
            $[id] = element;
            return true;
        }
    });
like image 98
Yairopro Avatar answered Feb 16 '23 01:02

Yairopro