Get index of clicked element using pure javascript

前端 未结 9 2010
渐次进展
渐次进展 2020-11-28 04:34

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++) {
           


        
9条回答
  •  粉色の甜心
    2020-11-28 04:57

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

提交回复
热议问题