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!
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);
})
}
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);
})
}
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