4

How can I get the index value of 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();    
};
Martin G
  • 17,357
  • 9
  • 82
  • 98
Faraz_pk
  • 53
  • 5
  • 1
    If you want to use `i` inside your function then you'll need to take a copy of it - see e.g. [JavaScript closures inside loops](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example). What exactly is it you want, though: `i` or `t[i]`? If it's the actual element that's been clicked on you can likely get that from the event. – Rup Apr 21 '15 at 14:56

1 Answers1

3

The first problem is you need to fix your use of <= in the loop, it is causing your loop to iterate one too many times (explaining the undefined messages). Change to < not <=:

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

It appears you just want to get a handle on the element, in the click event. In that case, the this context will refer to the clicked element.

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

If you really need the index then you'll need a closure, because otherwise i will always be the last iteration, by the time any click event occurs.

Closure 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 so you could change to:

var t = document.querySelectorAll(".table")  
MrCode
  • 63,975
  • 10
  • 90
  • 112
  • Thanks a lot for the hint. I could be able to get the index by using this.cellIndex as following code. function clickSchedule(){ var t = document.getElementsByClassName("table") for(i=0; i – Faraz_pk Apr 22 '15 at 11:07