I need to know the index of clicked element. Can\'t figure out how to do it
for (i = 0; i < document.getElementById(\'my_div\').children.length; i++) {
The accepted answer (from Ashwin Krishnamurthy) is actually far from optimal.
You can just do:
const g = document.getElementById('my_div');
for (let i = 0, len = g.children.length; i < len; i++)
{
g.children[i].onclick = function(){
alert(index) ;
}
}
to avoid creating unnecessary closures. And even then it's not optimal since you're creating 6 DOM event handlers (6 divs
in the example above) just to get a number of a single clicked div
.
What you should actually do is use an event delegation (attach single click event to the parent) and then check the e.target
's index using the method I've mentioned earlier and above (Get index of clicked element using pure javascript).