Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'); ... 
like image 618
unkown Avatar asked May 25 '12 07:05

unkown


People also ask

How do you clear a list in HTML?

HTML exampleAdding the "list-style: none" CSS class to the unordered list (<ul>) or ordered list (<ol>) tag removes any bullet or number.

Does Li have to be in UL?

Answer: yes it does, but with: ol or menu, that's all!

How can add Li in UL dynamically using jQuery?

Answer: Use the jQuery append() Method You can simply use the jQuery append() method to add <li> elements in an existing <ul> element. The following example will add a <li> element at the end of an <ul> on click of the button.


2 Answers

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 = ""; 
like image 162
Taha Paksu Avatar answered Oct 04 '22 18:10

Taha Paksu


You appear to be trying this with raw JavaScript:

while( root.firstChild ){   root.removeChild( root.firstChild ); } 

jQuery will only slow you down here.

like image 37
Sampson Avatar answered Oct 04 '22 18:10

Sampson