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.

ᴍᴇʜᴏᴠ
  • 4,804
  • 4
  • 44
  • 57

3 Answers3

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,756
  • 3
  • 19
  • 25
  • There [seems to be an even slightly shorter option](https://stackoverflow.com/a/54343121/722036). Either way, that did it. Thank you! – ᴍᴇʜᴏᴠ Jun 25 '19 at 11:05
0

I am gonna share my solution here.

function deleteAllOtherRowExceptOne(exceptionIndex) {
  const tableBody = document.querySelector('#my-table-tbody')
  const tableBodyRowLength = tableBody.rows.length

  let deleteIndex = 0
  for (let i = 0; i < tableBodyRowLength; i++) {
    if(i == exceptionIndex){
      deleteIndex++
    } else {
      tableBody.deleteRow(deleteIndex)
    }

  }
}
Jin Lim
  • 1,759
  • 20
  • 24
0

Here is my solution for this question.

// Fetch all rows
const rows = document.querySelectorAll('tr');

// Iterate through the rows and remove those that do not have the desired 
class
const className = 'class-name';
   rows.forEach(row => {
     if (!row.classList.contains(className)) {
       row.remove();
    }
});

I took refernce from here - https://bbbootstrap.com/code/delete-all-table-rows-except-one-given-class-javascript-61232938

Ask SNB
  • 11
  • 4