0

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?

2
  • $(this) is equal to $('.table-data tbody tr td' + ':nth-child(' + index + ')' ) Commented Sep 9, 2011 at 10:10
  • @JapanPro - yes, it took me a second to work that out - for loop. Commented Sep 9, 2011 at 10:12

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

4 Comments

$(this).addClass("nth-" + ++index ); will be perfect in my example! Very clever! thanks!
How to make it count from 0 in every row? Do I have to put this in double .each?
double .each look like the easy way - but not most pro programic. Thanks for your help!
Inside the "each" $(this) represents the current element. The .index() method returns the position of an element relative to its siblings - in the case of the jsbin example a set of three TD elements inside a TR (see api.jquery.com/index).
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.