Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symbol.iterator is not a function [duplicate]

<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 ?

like image 856
zloctb Avatar asked Jun 07 '16 10:06

zloctb


People also ask

What is Symbol Symbol iterator?

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.

What is an iterator function?

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.

What is symbol iterator in JS?

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) { }


1 Answers

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?

like image 126
Pranav C Balan Avatar answered Oct 04 '22 18:10

Pranav C Balan