Polymer: how to access elements in the "content" tag
I created a custom item, a list box with an inline filter:
Template for "filter list":
<template>
<content select="item"></content>
</template>
...
<filter-list filter='AAA'>
<item class="AAA">1</item>
<item class="AAA">2</item>
<item class="BBB">3</item>
<item class="BBB">4</item>
<item class="CCC">5</item>
<item class="CCC">6</item>
</filter-list>
The idea is that the list will show / hide items that match the class in the filter. For this purpose, I wrote the following callback:
Polymer('filter-list', {
filter: '',
ready: function() {
},
filterChanged: function() {
if(this.filter) {
items = this.$.items.querySelectorAll("."+this.filter);
console.log("Showing "+items.length+" items.");
}
},
});
But I am unable to navigate to the element nodes. items.length
always equal to 0. How can I get to item
-elements of the light DOM inside the custom element API?
source to share
You can access nodes that are inserted with a tag <content>
through a function getDistributedNodes()
.
Here's a small example of your scenario:
<polymer-element name="filter-list" attributes="filter">
<template>
<content id="items" select="item"></content>
</template>
<script>
Polymer('filter-list', {
ready: function() {
this.filter = '';
},
filterChanged: function() {
var items = this.$.items.getDistributedNodes();
for (var i = 0; i < items.length; ++i) {
items[i].style.display = items[i].className == this.filter ? 'block' : 'none';
}
}
});
</script>
</polymer-element>
<polymer-element name="my-app" noscript>
<template>
<input value="{{filter}}">
<filter-list filter="{{filter}}">
<item class="AAA">1</item>
<item class="AAA">2</item>
<item class="BBB">3</item>
<item class="BBB">4</item>
<item class="CCC">5</item>
<item class="CCC">6</item>
</filter-list>
</template>
</polymer-element>
<my-app></my-app>
You can enter a filter string in the input field. The filter is initially empty, so after loading the page, no items are displayed.
source to share