Reputation: 31
I'm trying to loop through a set of static paper-checkbox elements, but my code is failing with:
"Uncaught TypeError: this.querySelectorAll(...).forEach is not a function"
The relevant line of code is:
this.querySelectorAll('paper-checkbox').forEach(function(cb) {
I'm sure it's me being dumb - but what am I doing incorrectly in either selecting and/or iterating through the selected (static) checkboxes?
I'm effectively looking for the Polymer 1.0 alternative to JQuery's .each() function.
Many thanks!
Upvotes: 1
Views: 2092
Reputation: 517
The problem is this.querySelectorAll('paper-checkbox')
returns a NodeList, not an Array. They looks similar but they are different.
NodeList doesn't have the method foreach
on its prototype.
An easy solution is to convert your Nodelist to Array like this:
Array.prototype.slice.call(document.querySelectorAll('paper-checkbox'))
I suggest you to read this article in MDN on this topic.
Upvotes: 2
Reputation: 31
Thanks for the responses. I've just found the solution here.
Instead of:
this.querySelectorAll()
I should have been using:
Polymer.dom(this).querySelectorAll()
Works perfectly now!
Thanks again.
Upvotes: 2
Reputation: 16112
Answer: You need to use dom-repeat
.
"The dom-repeat element is a custom HTMLTemplateElement type extension that automatically stamps and binds one instance of template content to each object in a user-provided array."
<dom-module id="employee-list">
<template>
<div> Employee list: </div>
<template is="dom-repeat" items="{{employees}}">
<div>First name: <span>{{item.first}}</span></div>
<div>Last name: <span>{{item.last}}</span></div>
</template>
</template>
<script>
Polymer({
is: 'employee-list',
ready: function() {
this.employees = [{
first: 'Bob',
last: 'Smith'
}, {
first: 'Sally',
last: 'Johnson'
}, ...];
}
});
</script>
</dom-module>
Upvotes: 0
Reputation: 36
This is because
this.querySelector('paper-checkbox')
is null.
I think you need to go into the shadow root to get the elements e.g.
this.shadowRoot.querySelectorAll('paper-checkbox')
added:
this.shadowRoot.querySelectorAll('paper-checkbox').array().forEach(function(cb) {
Upvotes: 0