tags:

views:

24

answers:

3

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?

+1  A: 

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);
Rich
Thanks, I figured I was missing something fundamental if I couldn't figure out how to do something so simple.
MushinNoShin
+1  A: 

Sure, you could do it with the .slice method:

$('#TableID tr').slice(-2, -1).addClass('dark');

You can see it in action here.

Pat
Cool...didn't know about that one. +1
Rich
+2  A: 

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)
Anurag
Simply beautiful. Exactly what I was looking for.
MushinNoShin