从父节点删除所有子节点?

我有一个列表,我只想删除它的所有子节点。使用 jquery 最有效的方法是什么?这就是我所拥有的:

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


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

是否有捷径而不是一次一个地删除每个项目?

——————编辑————

每个列表元素都有一些附加的数据,以及类似下面这样的 click 处理程序:

$('#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());
}

最后,我可能会为每个列表项添加按钮-因此,看起来似乎是空()的方式去,以确保没有内存泄漏?

132490 次浏览

You can use .empty(), like this:

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

From the docs:

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

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.