Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove all child nodes from a parent?

Tags:

jquery

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?

like image 627
user246114 Avatar asked Jun 15 '10 11:06

user246114


People also ask

Will remove all child nodes of the set of matched elements from the DOM?

The empty() method removes all child nodes from the set of matched elements.

Which method is used to remove a child node from a parent node?

The removeChild() method of the Node interface removes a child node from the DOM and returns the removed node.

Which of the following options would you use to remove a child node in HTML using Javascript?

Modern Solution - child. remove()

How do I get rid of my last child?

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 .


1 Answers

You can use .empty(), like this:

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

From the docs:

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

like image 78
Nick Craver Avatar answered Oct 02 '22 13:10

Nick Craver