yglodt
yglodt

Reputation: 14551

Get reference to dynamically created element

In Polymer you can use this.$.idOfElement to get an element with an id of idOfElement.

How can I get a dynamically created element by its id if I only have the value of id in a variable?

Note: The element I want to reach out to is created dynamically like this:

<template is="dom-repeat" items="[[days]]" as="o">
    <my-custom-element id$="[[getId(o)]]"></my-custom-element>
</template>

I have plenty of these <my-custom-element> in my app and need to get hold of them one by one.

Edit:

None of these work, they all return undefined or null:

this.$[id]
this.$$(id)
this.root.querySelector('my-custom-element#' + id)
Polymer.dom(e.currentTarget).querySelector('my-custom-element#' + id)

Upvotes: 1

Views: 689

Answers (1)

Tomasz Pluskiewicz
Tomasz Pluskiewicz

Reputation: 3662

You cannot use the automatic node finder (this.$.x) for dynamic nodes. You have to use this.$$(selector), which acts like document.querySelector() constrained to children of the current element.

This why you must use this.$$('#' + nodeId) as suggested by Alan.

Polymer({
  is: 'my-elem',
  
  makeRed: function() {
    this.$$('#li2').style.color = 'red';
  }
});
<!DOCTYPE html>
<html>
<head>
  <base href="https://polygit.org/components/">
  <script src="webcomponentsjs/webcomponents-lite.min.js"></script>
  <link href="polymer/polymer.html" rel="import"/>
</head>

<body>
  <my-elem></my-elem>
  
  <dom-module id="my-elem">
    <template>
      <ul>
        <template is="dom-repeat" items='[ 1, 2, 3 ]'>
          <li id="li[[item]]">{{item}}</li>
        </template>
      </ul>
      
      <input type="button" value="make 2 red" on-tap="makeRed" />
    </template>
  </dom-module>

</body>
</html>

Upvotes: 4

Related Questions