开发者

What is the fastest way to remove child elements from the DOM in IE?

开发者 https://www.devze.com 2022-12-20 21:43 出处:网络
I am using jQuery, and have a table element that contains a few hundred rows. I want to remove all of the rows, and then add a new set of rows开发者_如何学JAVA. I do this by calling remove and then ap

I am using jQuery, and have a table element that contains a few hundred rows. I want to remove all of the rows, and then add a new set of rows开发者_如何学JAVA. I do this by calling remove and then append on the parent element.

My append logic is fairly fast, and follows the advice given here: http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly

However, the single call to remove takes 5 times as long as the append. What is the fastest way to clear the children of a dom element?

EDIT: Here is a condensed version of the code I use:

var table = $('#mytable');
$('tbody', table).remove();
table.append(tBodyContents.join(''));

tBodyContents is an array of strings, that when combined will form a the html for the rows in the tbody.


function emptyElement(element){
  var i = element.childNodes.length;
  while(i--){
    element.removeChild(element.lastChild);
  }
}

this one's actually quicker than the innerHTML trick, can be much quicker, depending on your browser. there are a few tests up on jsperf using similar functions that will give you some benchmarks...


I usually do

$('#myTableToEmpty').html('');

Then re-add rows where needed.


What about $('#tableId').empty()?

Documentation for empty method


If speed is really, really important, you're best of using innerHTML. $('tbody', table)[0].innerHTML = '';

I personally would just ignore jQuery alltogether, give the body an ID and just go for the document.getElementById('id').innerHTML = '' option. And offcourse still use jQuery for adding.


I confirm innerHTML is very much faster to remove huge html from an single element. In my case :

$('#main').html('');  // --> approx 5-6 seconds

$('#main').innerHTML=''; // --> a few milliseconds

Thanks for the tips

0

精彩评论

暂无评论...
验证码 换一张
取 消