Get index value from collection getElementsByClassName

How to get the index value of the getElementsByClassName collection.

function clickSchedule(){
    var t = document.getElementsByClassName("table")    
    for(i=0; i<=t.length; i++)
    {
        t[i].onclick= function() {

            // get the index value of the node when clicked something like this
            // alert(t[i].index)
            // already tried alert(t[i]) returning undefined.
            // already tried alert(t.item(i)) returning NULL.
    };
    }
}
window.onload = function(){
    clickSchedule();    
};

      

+3


source to share


1 answer


The first problem is that you need to fix the usage <=

in the loop, which is causing the loop to repeat itself too many times (explaining undefined messages). Go to <

not <=

:

for(i=0; i<t.length; i++)

      

You just seem to want to get the handle to the element on the click event. In this case, the context this

will refer to the clicked element.

t[i].onclick= function() {
    console.log( this );
}

      

If you really want an index, you need a closure, because otherwise i

it will always be the last iteration, by the time any click event occurs.



Closing example:

for(i=0; i<t.length; i++){
    (function(protectedIndex){
        t[i].onclick= function() {
            console.log( t[protectedIndex] );
        }
    })(i);
}

      

Note. document.querySelectorAll

has better browser support than document.getElementsByClassName

that, so you can change to:

var t = document.querySelectorAll(".table")  

      

+2


source







All Articles