clear table jquery

2020-05-11 21:05发布

I have an HTML table filled with a number of rows.

How can I remove all the rows from the table?

10条回答
Explosion°爆炸
2楼-- · 2020-05-11 21:34

Having a table like this (with a header and a body)

<table id="myTableId">
    <thead>
    </thead>
    <tbody>
   </tbody>
</table>

remove every tr having a parent called tbody inside the #tableId

$('#tableId tbody > tr').remove();

and in reverse if you want to add to your table

$('#tableId tbody').append("<tr><td></td>....</tr>");
查看更多
Evening l夕情丶
3楼-- · 2020-05-11 21:37

Slightly quicker than removing each one individually:

$('#myTable').empty()

Technically, this will remove thead, tfoot and tbody elements too.

查看更多
甜甜的少女心
4楼-- · 2020-05-11 21:39

Use .remove()

$("#yourtableid tr").remove();

If you want to keep the data for future use even after removing it then you can use .detach()

$("#yourtableid tr").detach();

If the rows are children of the table then you can use child selector instead of descendant selector, like

$("#yourtableid > tr").remove();
查看更多
Emotional °昔
5楼-- · 2020-05-11 21:45

I needed this:

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

It deletes all rows except the header.

查看更多
放我归山
6楼-- · 2020-05-11 21:46

The nuclear option:

$("#yourtableid").html("");

Destroys everything inside of #yourtableid. Be careful with your selectors, as it will destroy any html in the selector you pass!

查看更多
霸刀☆藐视天下
7楼-- · 2020-05-11 21:46
<table id="myTable" class="table" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Header 1</th>
            <th>Header 2</th>
            <th>Header 3</th>
        </tr>
    </thead>
    <tbody id="tblBody">

    </tbody>
</table>

And Remove:

$("#tblBody").empty();
查看更多
登录 后发表回答