<div id="par">
<span id="a1"></span>
<span id="a2"></span>
<div id="par2">
<span id="a3"></span>
<span id="a4"></span>
</div>
</div>
<script>
var ele = document.querySelectorAll('#par span');
for( var p of ele ){
console.log(p);
}
</script>
When i run this code I see error
Uncaught TypeError: ele[Symbol.iterator] is not a function
How to fix this problem ?
Symbol. iterator is the protocol that makes native objects like Array , Set , and Map iterable by providing a hook into language features like for…of loops and the spread operator. The most obvious use case is in creating new, iterable data structures that are not provided by the language, like a Linked List.
In JavaScript an iterator is an object which defines a sequence and potentially a return value upon its termination. Specifically, an iterator is any object which implements the Iterator protocol by having a next() method that returns an object with two properties: value. The next value in the iteration sequence.
A JavaScript iterable is an object that has a Symbol. iterator. The Symbol. iterator is a function that returns a next() function. An iterable can be iterated over with the code: for (const x of iterable) { }
Convert NodeList
to Array
for make it in iterable form, use Array.from()
to convert it.
<div id="par">
<span id="a1"></span>
<span id="a2"></span>
<div id="par2">
<span id="a3"></span>
<span id="a4"></span>
</div>
</div>
<script>
var ele = document.querySelectorAll('#par span');
for (var p of Array.from(ele)) {
console.log(p);
}
</script>
Refer the following question for more info : Are HTMLCollection and NodeList iterables?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With