Get index of clicked element using pure javascript

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).


Here is a piece of code that can help you get the index of the clicked element inside the for loop. All you need is a new scope:

var g = document.getElementById('my_div');
for (var i = 0, len = g.children.length; i < len; i++)
{

    (function(index){
        g.children[i].onclick = function(){
              alert(index)  ;
        }    
    })(i);

}

Edit 1: Incorporating user Felix Kling's comments into the answer.

event handler already is a closure

Edit 2: Updated fiddle link


With ES6 destructuring you can do

const index = [...el.parentElement.children].indexOf(el)

or

const index = Array.from(el.parentElement.children).indexOf(el)

or ES5 version

var index = Array.prototype.slice.call(el.parentElement.children).indexOf(el)