Jquery ——从一个非常大的表中删除所有行的最快方法

我认为这可能是删除一个非常大的表(3000行)的内容的一种快速方法:

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

但是在 Firefox 中完成大约需要5秒钟。我是否在做一些愚蠢的事情(除了尝试在浏览器中加载3000行) ?还有更快的方法吗?

178260 次浏览
$("#your-table-id").empty();

That's as fast as you get.

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.

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....

It's better to avoid any kind of loops, just remove all elements directly like this:

$("#mytable > tbody").html("");

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);
}

this works for me :

1- add class for each row "removeRow"

2- in the jQuery

$(".removeRow").remove();

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
$("#myTable > tbody").empty();

It won't touch the headers.