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?
The empty() method removes all child nodes from the set of matched elements.
The removeChild() method of the Node interface removes a child node from the DOM and returns the removed node.
Modern Solution - child. remove()
First, get the ul element with the id menu by using the getElementById() method. Then, remove the last element of the ul element by using the removeChild() method. The menu. lastElementChild property returns the last child element of the menu .
You can use .empty()
, like this:
$("#foo").empty();
From the docs:
Remove all child nodes of the set of matched elements from the DOM.
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