Remove all child nodes from a parent?

Jquery

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

You can use .empty(), like this:

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

From the docs: > Remove all child nodes of the set of matched elements from the DOM.

Solution 2 - Jquery

A other users suggested,

.empty()

is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.

If you wish to keep data, like event handlers for example, you should use

.detach()

as described on the JQuery's API detach documentation.

The method .remove() could be usefull for similar purposes.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser246114View Question on Stackoverflow
Solution 1 - JqueryNick CraverView Answer on Stackoverflow
Solution 2 - JqueryMarco OttinaView Answer on Stackoverflow