Delete all rows in an HTML table

后端 未结 19 1752
既然无缘
既然无缘 2020-12-04 12:03

How can I delete all rows of an HTML table except the \'s using Javascript, and without looping through all the rows in the table? I have a very huge

相关标签:
19条回答
  • 2020-12-04 12:11

    I needed to delete all rows except the first and solution posted by @strat but that resulted in uncaught exception (referencing Node in context where it does not exist). The following worked for me.

    var myTable = document.getElementById("myTable");
    var rowCount = myTable.rows.length;
    for (var x=rowCount-1; x>0; x--) {
       myTable.deleteRow(x);
    }
    
    0 讨论(0)
  • 2020-12-04 12:13

    Points to note, on the Watch out for common mistakes:

    If your start index is 0 (or some index from begin), then, the correct code is:

    var tableHeaderRowCount = 1;
    var table = document.getElementById('WRITE_YOUR_HTML_TABLE_NAME_HERE');
    var rowCount = table.rows.length;
    for (var i = tableHeaderRowCount; i < rowCount; i++) {
        table.deleteRow(tableHeaderRowCount);
    }
    

    NOTES

    1. the argument for deleteRow is fixed
    this is required since as we delete a row, the number of rows decrease.
    i.e; by the time i reaches (rows.length - 1), or even before that row is already deleted, so you will have some error/exception (or a silent one).

    2. the rowCount is taken before the for loop starts since as we delete the "table.rows.length" will keep on changing, so again you have some issue, that only odd or even rows only gets deleted.

    Hope that helps.

    0 讨论(0)
  • 2020-12-04 12:13

    This is an old question, however I recently had a similar issue.
    I wrote this code to solve it:

    var elmtTable = document.getElementById('TABLE_ID_HERE');
    var tableRows = elmtTable.getElementsByTagName('tr');
    var rowCount = tableRows.length;
    
    for (var x=rowCount-1; x>0; x--) {
       elmtTable.removeChild(tableRows[x]);
    }
    

    That will remove all rows, except the first.

    Cheers!

    0 讨论(0)
  • 2020-12-04 12:14

    If you have far fewer <th> rows than non-<th> rows, you could collect all the <th> rows into a string, remove the entire table, and then write <table>thstring</table> where the table used to be.

    EDIT: Where, obviously, "thstring" is the html for all of the rows of <th>s.

    0 讨论(0)
  • 2020-12-04 12:15

    Very crude, but this also works:

    var Table = document.getElementById("mytable");
    Table.innerHTML = "";
    
    0 讨论(0)
  • 2020-12-04 12:15

    Assign an id or a class for your tbody.

    document.querySelector("#tbodyId").remove();
    document.querySelectorAll(".tbodyClass").remove();
    

    You can name your id or class how you want, not necessarily #tbodyId or .tbodyClass.

    0 讨论(0)
提交回复
热议问题