Q:

Is there a way to select index of an array element on click?

I'm struggling about selecting a particular index of an element inside an array on click. Here's that peace of code and thanks in advance!
<div>

 <span class="dot"></span>
 <span class="dot"></span> -- lets say we click on this span
 <span class="dot"></span>
 <span class="dot"></span>
 <span class="dot"></span>

</div>

var dots = document.querySelectorAll(".dot");
for(var i = 0; i < dots.length; i ++){
dots[i].addEventListener("click", function(){
console.log(this) -- prints the actual html <span class="dot"></span>

// ?? How to print index of an element? To be more specific, in this case 
just "1" ??

})
}

A:

One way to achieve this is by adding a property (I named it dotIndex) to your dots and then console.log this property.
var dots = document.querySelectorAll(".dot");

for(var i = 0; i < dots.length; i ++){
    dots[i].dotIndex = i;
    dots[i].addEventListener("click", function(){
        console.log(this.dotIndex);
    })
}

Check the fiddle: https://jsfiddle.net/254uqtm0/
However, as Ori Drori suggested, you can just change var to let in your loop and it will work. If you are confused why, check this thread: What's the difference between using "let" and "var"?

