tags:

views:

40

answers:

1

Hi,

I have a list, I just want to remove all child nodes from it. What's the most efficient way using jquery? This is what I have:

<ul id='foo'>
  <li>a</li>
  <li>b</li>
</ul>

var thelist = document.getElementById("foo");   
while (thelist.hasChildNodes()){
    thelist.removeChild(thelist.lastChild);
}

is there a shortcut rather than removing each item, one at a time?

----------- Edit ----------------

Each list element has some data attached to it, and a click handler like this:

$('#foo').delegate('li', 'click', function() {
    alert('hi!');
});

// adds element to the list at runtime
function addListElement() {
    var element = $('<li>hi</hi>');
    element.data('grade', new Grade());
}

eventually I might add buttons per list item too - so it looks like empty() is the way to go, to make sure there are no memory leaks?

Thanks

Thanks

+6  A: 

You can use .empty(), like this:

$("#foo").empty();

From the docs:

Remove all child nodes of the set of matched elements from the DOM.

Nick Craver
Also worth noting (from docs) *To avoid memory leaks, jQuery removes other constructs such as data and event handlers from the child elements before removing the elements themselves.*
patrick dw
@patrick - +1, another reason to go this route over the often recommended `.html('')`, since data isn't stored on the element at all many people forget the leak that causes.
Nick Craver
+1 Also, if you are certain no events have been bound to the children of the parent `$("#foo")[0].innerHTML="";` will be faster. Just be careful you don't cause any memory leaks when doing removing elements this way (`empty()` already takes great care to ensure this doesn't happen, especially in IE).
David Murdoch
@David - The events would be a problem in all browsers, but good point, IE does have *other* memory issues, lots of them. Since the events are actually stored in `$.cache` with the rest of anything in data, it wouldn't get removed with the html setting calls.
Nick Craver
Ok updated question, yeah I do have some data associated with each element, so looks like empty() is the way to go.