从表中删除除特定行以外的所有行

Remove all but a specific row from a table

本文关键字:删除      更新时间:2023-09-26

我想从表中删除除id为'row0'的行以外的所有行:

<table class="mytable">
    <tr id="row0" class="myrow">
        <td>aaa</td>
    </tr>
    <tr class="myrow">
        <td>bbb</td>
    </tr>
    <tr class="myrow">
        <td>ccc</td>
    </tr>
</table>

但是下面的JQuery代码删除了所有行:

$('.mytable').children().not('#row0').remove();

有人能解释一下为什么会这样吗?我认为id为'row0'的子节点将被排除在外,但显然情况并非如此。

我已经找到了另一种方法来做到这一点,但仍然好奇为什么上面的方法不起作用:

$('.mytable').find('tr:not(#row0)').remove();

因为table元素的子元素是theadtfoottbody元素。tbody元素总是在生成的DOM中创建,即使它没有显式地写在HTML代码中。

你也可以这样做:

$('.mytable tr').not('#row0').remove();

$('#row0').siblings().remove();