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条回答
Melony?
2楼-- · 2020-05-11 00:06

Consider a table with id tbl: the jQuery code would be:

$('#tbl tr:not(:first)').remove();
查看更多
在下西门庆
3楼-- · 2020-05-11 00:07

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 had an TBODY element, you can do this:

$("someTableSelector > tbody:last").children().remove();

If you have THEAD or TFOOT elements you'll need to do something different.

查看更多
男人必须洒脱
4楼-- · 2020-05-11 00:12

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

$('someTableSelector tr:not(:first)').remove();
查看更多
一夜七次
5楼-- · 2020-05-11 00:16

This worked in the following way in my case and working fine

$("#compositeTable").find("tr:gt(1)").remove();
查看更多
混吃等死
6楼-- · 2020-05-11 00:19

To Remove all rows, except the first one (except header), use the below code:

$("#dataTable tr:gt(1)").remove();

查看更多
成全新的幸福
7楼-- · 2020-05-11 00:19

This works perfectly

$("#myTable tbody").children( 'tr:not(:first)' ).html("");
查看更多
登录 后发表回答