Iladarsda
Iladarsda

Reputation: 10696

jQuery, .each function question

I have following jQuery .each loop:

$('.table-data tbody tr td').each( function(index) {

    $('.table-data tbody tr td' + ':nth-child(' + index + ')' ).addClass( 'nth-' + index );


});

The problem is that it will work, but the last element of the .table-data tbody tr td' will not get a class. Why?

Is this because index is 0 based? How to make it loop for index + 1 time?

Upvotes: 0

Views: 415

Answers (2)

centralscru
centralscru

Reputation: 6690

You don't need to drill down to the current element using the index, it's easier than that!

$(".table-data tbody td").each(function(index){
    $(this).addClass("nth-" + index);
});

To renumber the TD elements within each row, try this.

$(".table-data tbody tr").each(function(index){
    $(this).find("td").each(function(index){
        $(this).addClass("nth-" + index);
    });
});

OR, if you want to be a bit cleverer, this...

$(".table-data tbody td").each(function(){
    $(this).addClass("n-" + $(this).index());
});

See this in action: http://jsbin.com/usaqix

Upvotes: 2

Timbo
Timbo

Reputation: 4533

The nth child starts on 1, so yes, your zero based index won't work correctly on it. You'll need to do index+1 where you use the index variable - but it will iterate the right number of times.

Upvotes: 0

Related Questions