Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 968
erorr Avatar asked Dec 01 '25 14:12

erorr


1 Answers

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();
like image 164
Felix Kling Avatar answered Dec 03 '25 04:12

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!