jquery - fastest way to remove all rows from a very large table

前端 未结 8 594
臣服心动
臣服心动 2021-01-30 09:40

I thought this might be a fast way to remove the contents of a very large table (3000 rows):

$jq(\"tbody\", myTable).remove();

But it\'s taking

相关标签:
8条回答
  • 2021-01-30 10:21
    $("#your-table-id").empty();
    

    That's as fast as you get.

    0 讨论(0)
  • 2021-01-30 10:24

    Two issues I can see here:

    1. The empty() and remove() methods of jQuery actually do quite a bit of work. See John Resig's JavaScript Function Call Profiling for why.

    2. The other thing is that for large amounts of tabular data you might consider a datagrid library such as the excellent DataTables to load your data on the fly from the server, increasing the number of network calls, but decreasing the size of those calls. I had a very complicated table with 1500 rows that got quite slow, changing to the new AJAX based table made this same data seem rather fast.

    0 讨论(0)
  • 2021-01-30 10:25

    if you want to remove only fast.. you can do like below..

    $( "#tableId tbody tr" ).each( function(){
      this.parentNode.removeChild( this ); 
    });
    

    but, there can be some event-binded elements in table,

    in that case,

    above code is not prevent memory leak in IE... T-T and not fast in FF...

    sorry....

    0 讨论(0)
  • 2021-01-30 10:26

    You could try this...

    var myTable= document.getElementById("myTable");
    if(myTable== null)
        return;
    var oTBody = myTable.getElementsByTagName("TBODY")[0];
    if(oTBody== null)
        return;
    try
    {
        oTBody.innerHTML = "";
    }
    catch(e)
    {
        for(var i=0, j=myTable.rows.length; i<j; i++)
            myTable.deleteRow(0);
    }
    
    0 讨论(0)
  • 2021-01-30 10:30

    Using detach is magnitudes faster than any of the other answers here:

    $('#mytable').find('tbody').detach();
    

    Don't forget to put the tbody element back into the table since detach removed it:

    $('#mytable').append($('<tbody>'));  
    

    Also note that when talking efficiency $(target).find(child) syntax is faster than $(target > child). Why? Sizzle!

    Elapsed Time to Empty 3,161 Table Rows

    Using the Detach() method (as shown in my example above):

    • Firefox: 0.027s
    • Chrome: 0.027s
    • Edge: 1.73s
    • IE11: 4.02s

    Using the empty() method:

    • Firefox: 0.055s
    • Chrome: 0.052s
    • Edge: 137.99s (might as well be frozen)
    • IE11: Freezes and never returns
    0 讨论(0)
  • 2021-01-30 10:31

    this works for me :

    1- add class for each row "removeRow"

    2- in the jQuery

    $(".removeRow").remove();
    
    0 讨论(0)
提交回复
热议问题