Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

javascript - remove all <li> from <ul>?

I am appending li in a ul using the following code:

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(root li);
root.removeChild('#listid li');
root.removeChild('ul li');
...
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you are using jQuery, why don't you use it's benefits?

adding <li> elements:

$("<li><img src='"+path[i]+"'></li>").appendTo(root);

removing all <li> elements:

$(root).empty();

deleting one <li> element:

$("li:eq(3)",$(root)).remove();

and if you are using raw js, you can use:

document.getElementById("root").innerHTML = "";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...