Javascript 从 <ul> 中删除所有 <li>?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10750137/
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
remove all <li> from <ul>?
提问by unkown
I am appending li
in a ul
using the following code:
我使用以下代码附加li
在 a 中ul
:
for (var i = 1; i <= len; i++) {
li = document.createElement('li');
element = document.createElement("img");
element.setAttribute("src", path[i]);
li.appendChild(element);
root.appendChild(li);
}
Now, I want to remove all items from the list on a button click. This is what I am using, which isn't working:
现在,我想通过单击按钮从列表中删除所有项目。这是我正在使用的,但不起作用:
while(root.hasChildNodes()){
root.removeChild('li');
}
The condition is true but the inner line root.removeChild('li')
doesn't work. I also tried these options:
条件为真,但内线root.removeChild('li')
不起作用。我也试过这些选项:
root.removeChild(root li);
root.removeChild('#listid li');
root.removeChild('ul li');
...
回答by Taha Paksu
If you are using jQuery, why don't you use it's benefits?
如果您正在使用 jQuery,为什么不使用它的好处呢?
adding <li>
elements:
添加<li>
元素:
$("<li><img src='"+path[i]+"'></li>").appendTo(root);
removing all <li>
elements:
删除所有<li>
元素:
$(root).empty();
deleting one <li>
element:
删除一个<li>
元素:
$("li:eq(3)",$(root)).remove();
and if you are using raw js, you can use:
如果您使用的是原始 js,则可以使用:
document.getElementById("root").innerHTML = "";
回答by Sampson
You appear to be trying this with raw JavaScript:
您似乎正在使用原始 JavaScript 尝试此操作:
while( root.firstChild ){
root.removeChild( root.firstChild );
}
jQuery will only slow you down here.
jQuery 只会让你慢下来。
回答by Sean H. Worthington
document.getElementById("the_ul_ID").innerHTML = "";
回答by Николай Солдаткин
What about?
关于什么?
var ul = root;
ul.innerHTML = '';
回答by thecodeparadox
$('#button').on('click', function() {
$(root).empty();
});
回答by wheresrhys
You need to fetch the elements before removing them as the native DOM methods (most of them anyway) can't be passed in selector strings the same way jQuery's methods can.
您需要在删除元素之前获取元素,因为本机 DOM 方法(无论如何它们中的大多数)不能像 jQuery 的方法一样在选择器字符串中传递。
var lis = root.getElementsByTagName("li");
for(var i = 0, il = lis.length;i<il;i++) {
root.removeChild(lis[i]);
}