erorr
erorr

Reputation: 43

Remove all but a specific row from a table

I want to remove all rows apart from the row with id 'row0' from a table:

<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>

But the following JQuery code removes ALL rows:

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

Could someone explain why this happens? I would think that the child with id 'row0' would be excluded, but obviously that's not the case.

I have found another way to do this but still curious why the above method doesn't work:

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

Upvotes: 3

Views: 495

Answers (1)

Felix Kling
Felix Kling

Reputation: 816364

Because the children of a table element are thead, tfoot or tbody elements. A tbody element is always created in the generated DOM, even if it is not explicitly written in the HTML code.

You can also do:

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

or

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

Upvotes: 8

Related Questions