How can I access node that have dynamic id value using Polymer node finding by id?
For example
<template>
<div id="{{ id }}"></div>
</template>
and in js
Polymer("my-element", {
ready: function() {
if (!this.id) {
this.id = 'id' + (new Date()).getTime();
}
console.log(this.$.id); // this part needs to find my div element
}
});
It's true that a JavaScript hash can be accessed using either dot
.
or array[]
notation. If you have a literal name, you can use dot notationthis.$.some_id
. If you have an indirection, likethis.id = 'some_id'
, then you can use array notationthis.$[this.id]
to find the same value.The tricky part is that Polymer only populates
$
array after first stamping the template, which happens beforeready
. If you had an external binding tothis.id
,this.$.[this.id]
would work, but since you are settingthis.id
inready
it's too late for the$
convenience.In this case, you can instead query your shadowRoot directly:
this.shadowRoot.querySelector('#' + this.id)
Pro tip: at some point a subclass may supply a new template, in which case
this.shadowRoot
will point to the new shadow-root and not the superclass version. For this reason, it's best to install a named div you can query against, e.g.this.$.id_div.querySelector('#' + this.id')
.You can use
$
like a hash:Polymer provides a method to this (source):
In your case, this should work:
If you are using Polymer 1.x then you can use
$$
.