The jQuery function removes all the rows except the first one using the remove() method. Syntax: $('#btn').
The jQuery remove() method is used to remove a row from HTML table. jQuery remove() Method: This method removes the selected elements alongwith text and child nodes. This method also removes data and events of the selected elements.
Removing all rows is different from removing the few rows. This can be done by using JavaScript. First of all set the ID or unique class to the table. Select the table element and use remove() or detach() method to delete the all table rows.
The Table deleteRow() method is used for removing a <tr> element from a table. In other words, Table deleteRow() method is used for deleting row(s) at the specified index in the table. index :It is used to specify the position of the row to be deleted.
This should work:
$(document).ready(function() {
$("someTableSelector").find("tr:gt(0)").remove();
});
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.
Another way to accomplish this is using the empty() function of jQuery with the thead and tbody elements in your table.
Example of a table:
<table id="tableId">
<thead>
<tr><th>Col1</th><th>Col2</th></tr>
</thead>
<tbody>
<tr><td>some</td><td>content</td></tr>
<tr><td>to be</td><td>removed</td></tr>
</tbody>
</table>
And the jQuery command:
$("#tableId > tbody").empty();
This will remove every rows contained in the tbody element of your table and keep the thead element where your header should be. It can be useful when you want to refresh only the content of a table.
If it were me, I'd probably boil it down to a single selector:
$('someTableSelector tr:not(:first)').remove();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With