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

I have a table and I want to delete all <tr> tables except the first one. How can i do this?

+4
source share
6 answers

There are several methods, the most difficult is to use the selector :gt() , for example:

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

Does it make sense in the first line? I am going to go on a limb and say that the first row is most likely the row that contains the column headings.

If so, one simple option is to put the first line in <thead> and all body lines in <tbody> . Then you can simply do:

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

It also gives your HTML more meaning.

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

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

The right CSS selector is important because it will allow jQuery / Sizzle to successfully use its own querySelectorAll method, which will provide extremely fast selection.

querySelectorAll supported in many browsers, including IE8 .


EDIT:

Although you asked about the jQuery solution, I thought that I would choose the native DOM API solution, as it will work faster than anything else, and it is really very simple.

 var rows = document.getElementById('theTable').rows; while( rows[1] ) rows[1].parentNode.removeChild( rows[1] ); 
+3
source

I think I will go on the bandwagon and provide some solutions:

If you use thead for the first line, just omit tr in tbody :

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

If you are not using thead , you can get the following lines in different ways. I highly recommend checking out the jQuery api

Here are some examples of how you can delete rows:

  • $('#myTable tr + tr').remove();
  • $('#myTable tr:gt(0)').remove();
  • $('#myTable tr:not(:first-child)').remove();
  • $('#myTable').find('tr').not(':first-child').remove();
  • $('#myTable tr:first-child').siblings().remove();

Indeed, it comes down to how creatively you want to be in your selectors and what your intentions are. I did not provide an example of a filter, but using filter will allow you to call end and continue the chain from the parent element.

You will need to perform some unit tests to find out which of these methods is the fastest, or not if it is not so important.

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

Example:

http://jsfiddle.net/TwqN3/

+1
source

Use the following sibling selector :

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

Example: http://jsfiddle.net/TwqN3/2/ (Thanks Stefan Kendall! I did not know jsfiddle.)

0
source

Source: https://habr.com/ru/post/1334030/


All Articles