Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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

like image 974
bluemoo Avatar asked Feb 19 '10 19:02

bluemoo


People also ask

How do you remove child element from DOM?

Child nodes can be removed from a parent with removeChild(), and a node itself can be removed with remove(). Another method to remove all child of a node is to set it's innerHTML=”” property, it is an empty string which produces the same output.

Which method can be used to remove an element from the DOM?

HTML DOM Element remove() The remove() method removes an element (or node) from the document.

Will remove all child nodes of the set of matched elements from the DOM?

To remove all child nodes from a parent, use the empty() method. The empty() method removes all child nodes from the set of matched elements.


2 Answers

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

like image 163
market Avatar answered Sep 28 '22 06:09

market


I usually do

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

Then re-add rows where needed.

like image 41
Alex Bagnolini Avatar answered Sep 28 '22 07:09

Alex Bagnolini