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
  • 1
  • 9

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
  • 1,900
  • 6
  • 11
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
  • 120,546
  • 16
  • 121
  • 140
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
  • 959,406
  • 173
  • 1,780
  • 1,769
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
  • 15,427
  • 16
  • 64
  • 91
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
  • 943
  • 12
  • 23