tags:

views:

288

answers:

3

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.

+5  A: 

I usually do

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

Then re-add rows where needed.

Alex Bagnolini
Probably faster than $('#myTableToEmpty tr').remove()
ryanulit
I do the same thing. It's simple and fast. +1
Bill Paetzke
Does this method clear out bound events and jQuery data as well? That is one thing that (according to the docs) the remove() function does. EDIT: From the docs - *In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.*
patrick dw
This doesn't seem to be any faster in my case than using remove, but I'll look into it futher.
A: 

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

Documentation for empty method

PatrikAkerstrand
A: 

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.

douwe
I get a "Unknown runtime error" when I try this. I'll see if I can figure out what I'm doing wrong.