How to remove all the <tr> from a table except the first one using jquery

北战南征 提交于 2020-01-14 12:50:05

问题


I am having a table and I want to remove all <tr> of the table except the first one. How can I do this.?


回答1:


There are several methods here, the most terse is to use the :gt() selector, like this:

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



回答2:


Is there a special meaning to the first row? I am going to go out on a limb and say the first row is likely the row which contains the column headings.

If so, one easy option is to put the first row in a <thead> and all the body rows in a <tbody>. Then you could simply do:

$('#myTable tbody tr').remove();

This also gives your HTML more semantic meaning.




回答3:


I guess I'll jump on the bandwagon and provide some solutions:

If you're using thead for the first row, just drop the trs in the tbody:

$('#myTable tbody tr').remove();

If you're not using thead you can get the subsequent rows in numerous ways. I highly suggest looking through the jQuery api

Here are a few examples of how you can remove the rows:

  1. $('#myTable tr + tr').remove();
  2. $('#myTable tr:gt(0)').remove();
  3. $('#myTable tr:not(:first-child)').remove();
  4. $('#myTable').find('tr').not(':first-child').remove();
  5. $('#myTable tr:first-child').siblings().remove();

Really it comes down to how creative you want to be in your selectors, and what your intentions are. I didn't provide a filter example, but using filter will allow you to call end and continue chaining from a parent element.

You'll have to do some unit-tests to see which of these methods are the fastest, or don't if it's not as important.




回答4:


$('#theTable tr').slice(1).remove();

This uses a fully valid CSS selector to get all the table rows, then takes a .slice() of the set starting with index 1 (the second row), and finally calls .remove() to remove the rows.

The valid CSS selector is important because it will allow jQuery/Sizzle to successfully utilize the native querySelectorAll method, which will provide an extremely fast selection.

querySelectorAll is supported in many browsers, including IE8.


EDIT:

Though you asked for a jQuery solution, I thought I'd throw in a native DOM API solution since it will perform faster than anything else, and it's really pretty simple.

var rows = document.getElementById('theTable').rows;

while( rows[1] )
    rows[1].parentNode.removeChild( rows[1] );



回答5:


$('#myTable').find('tr').not(":first").remove();

Example:

http://jsfiddle.net/TwqN3/




回答6:


Use the next siblings selector:

$('table :first-child ~ tr').remove();

Example: http://jsfiddle.net/TwqN3/2/ (Thanks to Stefan Kendall! I didn't knew jsfiddle.)



来源:https://stackoverflow.com/questions/4582173/how-to-remove-all-the-tr-from-a-table-except-the-first-one-using-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!