views:

18580

answers:

4

Using jQuery, how do I delete all rows in a table except the first? This is my first attempt at using index selectors. If I understand the examples correctly, the following should work:

$(some table selector).remove("tr:gt(0)");

which I would read as "Wrap some table in a jQuery object, then remove all 'tr' elements (rows) where the element index of such rows is greater than zero". In reality, it executes without generating an error, but doesn't remove any rows from the table.

What am I missing, and how do I fix this? Of course, I could use straight javascript, but I'm having so much fun with jQuery that I'd like to solve this using jQuery.

+32  A: 

This should work:

$(document).ready(function() {
   $("someTableSelector").find("tr:gt(0)").remove();
});
Strelok
Many thanks -- that worked perfectly.
Ken Paul
+2  A: 

Your selector doesn't need to be inside your remove.

It should look something like:

$("#tableID tr:gt(0)").remove();

Which means select every row except the first in the table with ID of tableID and remove them from the DOM.

CMPalmer
I agree. In my case, the table object had been previously selected.
Ken Paul
+17  A: 

I think this is more readable given the intent:

$('someTableSelector').children( 'tr:not(:first)' ).remove();

Using children also takes care of the case where the first row contains a table by limiting the depth of the search.

If you have THEAD, TFOOT, and TBODY elements you'll need to do something different -- in that case, I suspect you'll leave the THEAD alone and remove all rows from TBODY and TFOOT elements.

tvanfosson
I agree -- thanks. I wish I could award multiple answers.
Ken Paul
+5  A: 

If it were me, I'd probably boil it down to a single selector:

$('someTableSelector tr:not(:first)').remove();
Dave Ward