Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery - get all rows except the first and last

i want to dynamically add a class to all rows of a table except the first and last row. how would i do this without assigning a css class to the rows to identify them. I am getting all but the first row currently with

$("#id").find("tr:gt(0)")

i need to combine this with not("tr:last") somehow maybe?

like image 757
user210757 Avatar asked Feb 12 '10 17:02

user210757


3 Answers

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!

like image 162
Tatu Ulmanen Avatar answered Oct 26 '22 21:10

Tatu Ulmanen


Try this:

.not(':first').not(':last')
like image 16
mikkelz Avatar answered Oct 26 '22 21:10

mikkelz


why not just this?

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

works as pure CSS selector as well.

like image 16
ProblemsOfSumit Avatar answered Oct 26 '22 23:10

ProblemsOfSumit