Polymer 1.0: Accessing elements by id in dom-repeat -


this question has almost been asked here, main difference being want access elements id through polymer's this.$ syntax. there is answer on linked question says how this, doesn't work in instance, , don't think there's special i'm doing (which makes me think answer wrong). edit: i've answered question solution here recommended, think specificity of using element id still warrants question being separate.

so, onto question. have following setup:

<div id="anelement">content</div> <template is="dom-repeat" items="{{myitems}}">   <div id="{{item.name}}>{{item.content}}</div> </template> <button on-click="listelements"></button>  ...  properties: {   myitems: {     type: array,     value: function() {       return [         { name: "item1", content: "first item" },         { name: "item2", content: "second item" }       ]     }   } },  listelements: function(e) {   console.log("this.$: ", this.$); } 

output on button click:

this.$:    anelement: div#anelement.style-scope 

i can inspect html on resulting page , see there 2 <div>'s have expected id's of item1 , item2, yet not listed in output listelements.

in actuality, elements in dom-repeat other custom elements methods need access , use in click handler, not being access them directly issue.

i've inspected of polymer documentation, , haven't found reason why case.

well, after little more digging through documentation, answer right there. thought i'd share since have seen answers out there wrong!

from documentation on node finding in local dom:

polymer automatically builds map of statically created instance nodes in local dom, provide convenient access used nodes without need query them manually. node specified in element’s template id stored on this.$ hash id.

note: nodes created dynamically using data binding (including in dom-repeat , dom-if templates) not added this.$ hash. hash includes statically created local dom nodes (that is, nodes defined in element’s outermost template).

...

for locating dynamically-created nodes in element’s local dom, use $$ method:

this.$$(selector)

$$ returns first node in local dom matches selector.

(emphasis in above text mine)

my own personal note:

note: notice this.$$ not object, method. therefore, printing elements id not doable this.$$, locating specific dynamically-created element is, need - , need :)

note 2: adding after taking own advice , using this.$$(selector). remember selector, if looking element id, remember preface #, i.e. this.$$('#myelement')!


Comments

Popular posts from this blog

javascript - jQuery: Add class depending on URL in the best way -

caching - How to check if a url path exists in the service worker cache -

Redirect to a HTTPS version using .htaccess -