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.
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.
HTML DOM Element remove() The remove() method removes an element (or node) from the document.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With