javascript javascript删除li而不删除ul?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18795028/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript remove li without removing ul?
提问by MAZUMA
Is there any way to remove the li elements of a ul without also removing the ul? I can only seem to find this.
有没有办法在不删除 ul 的情况下删除 ul 的 li 元素?我似乎只能找到这个。
var element = document.getElementById('myList');
element.parentNode.removeChild(element);
But, this removes the ul. I'm hoping to be able to remove and append li elements on the fly without also having to createElement the ul every time I remove li elements. Just looking for a simpler way. Thanks for any help.
但是,这会删除 ul。我希望能够即时删除和附加 li 元素,而不必每次删除 li 元素时都创建 ul 元素。只是寻找更简单的方法。谢谢你的帮助。
<div id="listView">
<ul id="myList" class="myList-class">
<li>item 1</li>
<li>item 2</li>
</ul>
</div>
回答by Justin Wood
You can do something like this.
你可以做这样的事情。
var myList = document.getElementById('myList');
myList.innerHTML = '';
If you are using jQuery
如果你使用 jQuery
$('#myList').empty();
Both of these will remove EVERYTHING inside the list.
这两个都将删除列表中的所有内容。
回答by Krasimir
This should do the trick:
这应该可以解决问题:
var lis = document.querySelectorAll('#myList li');
for(var i=0; li=lis[i]; i++) {
li.parentNode.removeChild(li);
}
回答by Ben Hymanson
The reason it's removing the ul
is because you have the element
variable pointing to the ul
. Your next line of code then moves up to the parent (#listView
) and applies the removechild
method with the element
variable (which points to ul
element) passed to it.
它删除 的原因ul
是因为您有element
指向ul
. 然后您的下一行代码向上移动到父级 ( #listView
) 并应用传递给它removechild
的element
变量(指向ul
元素)的方法。
If you need to remove all the li elements then you can use:
如果您需要删除所有 li 元素,则可以使用:
document.getElementById('myList').innerHTML = '';
which will empty the ul
completely. If you need to remove selected li
elements then you can traverse from #myList
to the particular child elements using something like:
这将ul
完全清空。如果您需要删除所选li
元素,则可以使用以下内容遍历#myList
特定子元素:
var ulElem = document.getElementById('myList');
ulElem.removeChild(ulElem.childNodes[i])
where i
is the index of the li
you want to remove (0 for 1st, 1 for 2nd, etc.)
您要删除i
的索引在哪里li
(0 代表第一个,1 代表第二个,等等)
For reference: https://developer.mozilla.org/en-US/docs/Web/API/Node.removeChild
供参考:https: //developer.mozilla.org/en-US/docs/Web/API/Node.removeChild
回答by liron_hazan
As long as we have a first child - remove it. (which will be as long as we have even one member).
只要我们有第一个孩子 - 删除它。(只要我们有一个成员)。
const removeNodesFromList = () => {
const nodes = document.querySelector('.ul-class-selector');
while (nodes.firstChild) {
nodes.removeChild(nodes.firstChild);
}
};