jQuery delete all table rows except first

2020-05-10 23:35发布

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.

14条回答
相关推荐>>
2楼-- · 2020-05-11 00:20

$("#p-items").find( 'tr.row-items' ).remove();
查看更多
爷的心禁止访问
3楼-- · 2020-05-11 00:21

-Sorry this is very late reply.

The easiest way i have found to delete any row (and all other rows through iteration) is this

$('#rowid','#tableid').remove();

The rest is easy.

查看更多
何必那么认真
4楼-- · 2020-05-11 00:23

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.

查看更多
Bombasti
5楼-- · 2020-05-11 00:23
$('#table tr').slice(1).remove();

I remember coming across that 'slice' is faster than all other approaches, so just putting it here.

查看更多
再贱就再见
6楼-- · 2020-05-11 00:24

Easiest way :

$("#mytable").find($("tr")).slice(1).remove()

-first reference the table
-get the list of elements and slice it and remove the selected elements of the list

查看更多
乱世女痞
7楼-- · 2020-05-11 00:25

This should work:

$(document).ready(function() {
   $("someTableSelector").find("tr:gt(0)").remove();
});
查看更多
登录 后发表回答