清除/清空 tbody 元素的所有内容?

我认为这将是相当简单的,但似乎空的方法不工作,以清除一个身体,我有。如果有人知道这样做的正确方法,我将不胜感激,我只是想删除 tbody 中包含的所有内容。到目前为止,我一直在尝试:

$("#tbodyid").empty();

HTML:

<table>
<tbody id="tbodyid">
<tr><td>something</td></tr>
</tbody>
</table>

注意: 我试图做到这一点,以集成一个插件由别人写的,我正在使用一个项目。我正在生成新的 <tr><td>new data</td></tr>服务器端,希望能够清除现有的表行,并在 AJAX 回调中替换它们。

232357 次浏览

jQuery:

$("#tbodyid").empty();

HTML:

<table>
<tbody id="tbodyid">
<tr>
<td>something</td>
</tr>
</tbody>
</table>

Works for me
http://jsfiddle.net/mbsh3/

You probably have found this out already, but for someone stuck with this problem:

$("#tableId > tbody").html("");
        <table id="table_id" class="table table-hover">
<thead>
<tr>
...
...
</tr>
</thead>
</table>

use this command to clear the body of that table: $("#table_id tbody").empty()

I use jquery to load the table content dynamically, and use this command to clear the body when doing the refreshing.

hope this helps you.

you can use the remove() function of the example below and build table again with table head, and table body

$("#table_id  thead").remove();
$("#table_id  tbody").remove();

Without use ID (<tbody id="tbodyid">) , it is a great way to cope with this issue

$('#table1').find("tr:gt(0)").remove();

PS:To remove specific row number as following example

$('#table1 tr').eq(1).remove();

or

$('#tr:nth-child(2)').remove();

Example for Remove table header or table body with jquery

function removeTableHeader(){
$('#myTableId thead').empty();
}


function removeTableBody(){
$('#myTableId tbody').empty();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='myTableId'  border="1">
<thead>
<th>1st heading</th>
<th>2nd heading</th>
<th>3rd heading</th>
</thead>
<tbody>
<tr>
<td>1st content</td>
<td>1st content</td>
<td>1st content</td>
</tr>
<tr>
<td>2nd content</td>
<td>2nd content</td>
<td>2nd content</td>
</tr>
<tr>
<td>3rd content</td>
<td>3rd content</td>
<td>3rd content</td>
</tr>
</tbody>
</table>
<br/>
<form>
<input type='button' value='Remove Table Header' onclick='removeTableHeader()'/>
<input type='button' value='Remove Table Body' onclick='removeTableBody()'/>
</form>

$('#tableId').find("tr:gt(0)").remove();

This will not remove headers, it will clear only the table body.