Search code examples
javascripthtmlhtml-table

Delete all rows in an HTML table


How can I delete all rows of an HTML table except the <th>'s using Javascript, and without looping through all the rows in the table? I have a very huge table and I don't want to freeze the UI while I'm looping through the rows to delete them


Solution

  • Keep the <th> row in a <thead> and the other rows in a <tbody> then replace the <tbody> with a new, empty one.

    i.e.

    var new_tbody = document.createElement('tbody');
    populate_with_new_rows(new_tbody);
    old_tbody.parentNode.replaceChild(new_tbody, old_tbody)