jquery - get all rows except the first and last

Solution 1:

Drop the gt(), as I'd assume it's a tiny bit slower than :first.

Use not() in conjunction with :first and :last:

$('table#tbl > tbody > tr').not(':first').not(':last').addClass('highlight');

Most browsers automatically add an tbody element in the table markup if that's missing, that is why the immediate children selector was failing – there were no <tr> elements as an immediate children to the <table> tag.

I am not 100% sure this is the way all browsers do it, so it would be safer to just add the <tbody> manually. Otherwise you need a little sniffing and cannot do it as an one liner:

if($('table#tbl > tbody').size() > 0) {
    $('table#tbl > tbody > tr').not(':first').not(':last').addClass('highlight');
} else {
    $('table#tbl > tr').not(':first').not(':last').addClass('highlight');
}

Hope this solves your problem!

Solution 2:

Try this:

.not(':first').not(':last')

Solution 3:

why not just this?

$('table tr:not(:first-child):not(:last-child)');

works as pure CSS selector as well.

Solution 4:

You can combine the .not() methods into one by separating the selectors with commas:

$('#id tr').not(':first, :last');
$('#id tr:not(:first, :last');

Note that the second one is not valid in pure CSS, only as a jQuery selector. For pure CSS you'd have to use @Sumit's answer.