Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript find index of div

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!

like image 512
Jakub Matwiejew Avatar asked Nov 23 '25 22:11

Jakub Matwiejew


2 Answers

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);
 })
}
like image 152
Christopher Messer Avatar answered Nov 25 '25 11:11

Christopher Messer


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);
  })
}
like image 25
Jonas Wilms Avatar answered Nov 25 '25 12:11

Jonas Wilms



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!