Get index of clicked element using pure javascript

前端 未结 9 2007
渐次进展
渐次进展 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).

    0 讨论(0)
  • 2020-11-28 04:58
    for (let i = 0; i < childNodes.length; i++){
          (function(index){
            childNodes[i].addEventListener("click", myScript);
            function myScript(){
              console.log(index);
            }
          })(i);
        }
    
    0 讨论(0)
  • 2020-11-28 05:02

    The index in relationship to what ?

    If it is about the index within the current HTML collection, the index would just be represented with your i counter variable.

    One word of caution: Since HTMLCollections are "Live", you should ever use them to figure out the .length within a loop. If it happens to be that those elements are added or removed within the loop, strange and dangerous things can happen. Cache the .length value before calling the loop instead.

    0 讨论(0)
  • 2020-11-28 05:04

    Table cell elements have a cellIndex property, but I don't know about other elements. You will either have to

    • create a closure to reserve the value of i
    • dynamically count previousSiblings
    • add an index property in your for-loop and read that (don't augment host objects).

    The closure approach will be the easiest, I think. Please make sure you have understood how closures work, there are good explanations on the web.

    function makeAlertNumber(element, i) {
        element.addEventListener('click', function() {
           alert('Number ' + i + ' was clicked');
        }, false);
    }
    [].slice.call(document.getElementById('container').children).forEach(makeAlertNumber); // homework: find a way to express this for older browsers :-)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-28 05:09

    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

    0 讨论(0)
提交回复
热议问题