3

That's my first question here so please don't hate me :) Tried to look for it but I wasn't able to find what I need. How can I print index of div with class .circle that has been clicked? Here's my code

var circle = document.querySelectorAll(".circle");

for(i=0; i<circle.length; i++){

 circle[i].addEventListener("click", function(){
   this.classList.toggle("hide");
   console.log(circle.indexOf(this));
 })
}

Thanks!

Jakub Matwiejew
  • 107
  • 2
  • 11

5 Answers5

2

Make sure you use let in your for loop and just console.log(i)

var circle = document.querySelectorAll(".circle");

for(let i=0; i<circle.length; i++){

 circle[i].addEventListener("click", function(){
   this.classList.toggle("hide");
   console.log(i);
 })
}
Christopher Messer
  • 2,040
  • 9
  • 13
1

Just a small change: Simply convert the NodeList into an Array ( Arrays have an indexOf function):

 var circle = Array.from(document.querySelectorAll(".circle"));

Try it

Alternatively, you could simply take the index of the iteration:

 var circle = document.querySelectorAll(".circle");

for(let i=0; i<circle.length; i++){
 circle[i].addEventListener("click", function(){
   this.classList.toggle("hide");
   console.log(i);
  })
}
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

If by "index" you mean its index in the collection returned by that querySelectorAll call, you can use querySelectorAll's forEach (which is relatively new, but polyfillable):

var circle = document.querySelectorAll(".circle");
circle.forEach(function(circle, index) {
 circle.addEventListener("click", function(){
   this.classList.toggle("hide");
   console.log(index);
});
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
0

Since you loop through your elements with the i as an iterator, just declare i as a different variable by using let in you for loop and then you can just use console.log(i) to show each circle's index:

var circle = document.querySelectorAll(".circle");

for(let i=0; i<circle.length; i++){

    circle[i].addEventListener("click", function(){
        this.classList.toggle("hide");
        console.log(i);
    })
}
Koby Douek
  • 16,156
  • 19
  • 74
  • 103
0

May be useful for someone, the same solution in ES5, using closures:

var circle = document.querySelectorAll(".circle");

for(var i=0; i<circle.length; i++){
    (function(i) {
        circle[i].addEventListener("click", function(){
            this.classList.toggle("hide");
            console.log(i);
        });
    })(i);
}
Manish Kumar
  • 1,131
  • 15
  • 28