I know I can use this code below to delete a single row from an html table:
$(this).closest("tr").remove();
but I now want to have a quick way of removing all rows (so it just leaves the headers) on an html 开发者_运维技巧table at once. Something like:
$("#myTable tr").remove();
Is there any syntax for this or do I need to loop through each row and delete them one by one?
I'd do it like this...
$('#myTable > tbody').empty();
This will leave your tbody
element empty.
Created a jsperf out of curiousity. http://jsperf.com/jquery-clear-a-table
Oddly enough, the code you posted appears to be slightly more efficient. It's all really close though, so I'd just use whatever makes the most sense as far as readability.
I wound up using:
$("#myTable").find("tr:gt(0)").remove();
if I understand you correctly you'd ;like to remove all rows but not the first, or if you have tbody inside of your table all rows in tbody. Since you're using closest I presume you're coding inside some event so in this case you can use the following:
$('tr', $(this).closest('tbody')).remove();
//or using your table
$('tr:not:first', '#mytable').remove();
精彩评论