1

I have a table rendered dynamically. There's one <tr class="dolly"> somewhere inside its <tbody> that serves as a reference row - it gets cloned and filled with data later. I need to delete all rows except that one.

What I tried:

  • for loop: uses an increment which quickly gets invalid as the rows are deleted
  • while loop: continues until all rows are deleted, which never happens because of the condition

Please let me know if you have any ideas. Please no jQuery.

mehov
  • 4,178
  • 3
  • 40
  • 55

1 Answers1

2

use document.querySelectorAll('tr:not(.dolly)') to select all tr's except with class .dolly and then iterate over it to remove the filtered tr's.

document.querySelectorAll('table tr:not(.dolly)').forEach((tr) => {
    tr.remove();
});
<table>
  <tr class="dolly">
    <td>One</td>
  </tr>
  <tr>
    <td>Two</td>
  </tr>
  <tr>
    <td>Three</td>
  </tr>
</table>
random
  • 7,296
  • 2
  • 17
  • 25
  • There [seems to be an even slightly shorter option](https://stackoverflow.com/a/54343121/722036). Either way, that did it. Thank you! – mehov Jun 25 '19 at 11:05