Reputation: 4886
I'd like to be grab the next to last TR in a table.
$("#TableID tr:last")
gets the very last one, is there some way I can get the TR prior to that one?
Upvotes: 6
Views: 3335
Reputation: 141919
When a negative index is specified for eq, it starts counting backwards from the end.
.eq( -index )
-index An integer indicating the position of the element, counting backwards from the last element in the set.
$('#TableID tr').eq(-2)
Upvotes: 17
Reputation: 25685
Sure, you could do it with the .slice method:
$('#TableID tr').slice(-2, -1).addClass('dark');
You can see it in action here.
Upvotes: 3
Reputation: 36866
The selector is a string. You can build out the selector string using a combination of the nth-child function and the .length property, or you can get all tr children and pick out the 2nd to last item with get().
var selector = "#TableID tr";
var second_to_last = $(selector).length - 2; // using 2 because it's 0 based
$(selector).get(second_to_last);
Upvotes: 1