Get index of clicked element using pure javascript

前端 未结 9 2018
渐次进展
渐次进展 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 05:07

    I had the same issue where I needed to loop through an array and get the index number of the item clicked.

    Here is how I solved the issue...

    //first store array in a variable
    let container = [...document.getElementById('container')];
    
    //loop through array with forEach function
    container.forEach((item,index) => {
        item.addEventListener('click', () => console.log(index));
    });
    

    This will console.log the index number of the item clicked on.

    Hope this answers some questions.

提交回复
热议问题