Only the last element is bound/inserted/etc. in your javascript code’s “for” loop

There is a common problem when you use javascript for loop to bind an event function or add a class that comes from looping selection’s attributes.

To make clear what I mean consider this example:

var lis = $('ul li');

for (var i = 0; i<lis.length; i++) {
    var id = lis[i].id;
    lis[i].onclick = function () {
        alert(id);
    };
} // All li's get and alert the last li's id

There is no obvious code syntax nor logical problem in this code. But you still will get last li’s id in alert window whichever li you click.

The solution to this problem is to rewrite your code similar to this one:

var lis = $('ul li');

for (var i = 0; i<lis.length; i++) {
    var id = lis[i].id;
    lis[i].onclick = function (the_id) {
        return function () {
            alert(the_id);
        };
    }(id);
}

Here, we are introducing another anonymous function which will be called immediately after it has been declared, because of the trailing () (in our case (id)) with the current id.

This solves the problem of all items in the loop getting the last arrays/elements/etc. attribute value (id/class/etc.).