Delete all rows in an HTML table

后端 未结 19 1753
既然无缘
既然无缘 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:19

    this is a simple code I just wrote to solve this, without removing the header row (first one).

    var Tbl = document.getElementById('tblId');
    while(Tbl.childNodes.length>2){Tbl.removeChild(Tbl.lastChild);}
    

    Hope it works for you!!.

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

    How about this:

    When the page first loads, do this:

    var myTable = document.getElementById("myTable");
    myTable.oldHTML=myTable.innerHTML;
    

    Then when you want to clear the table:

    myTable.innerHTML=myTable.oldHTML;
    

    The result will be your header row(s) if that's all you started with, the performance is dramatically faster than looping.

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

    Assing some id to tbody tag. i.e. . After this, the following line should retain the table header/footer and remove all the rows.

    document.getElementById("yourID").innerHTML="";
    

    And, if you want the entire table (header/rows/footer) to wipe out, then set the id at table level i.e.

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

    This works in IE without even having to declare a var for the table and will delete all rows:

    for(var i = 0; i < resultsTable.rows.length;)
    {   
       resultsTable.deleteRow(i);
    }
    
    0 讨论(0)
  • 2020-12-04 12:24

    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)
    
    0 讨论(0)
  • 2020-12-04 12:24

    the give below code works great. It removes all rows except header row. So this code really t

    $("#Your_Table tr>td").remove();
    
    0 讨论(0)
提交回复
热议问题