unkown
unkown

Reputation: 1128

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');
...

Upvotes: 60

Views: 127055

Answers (7)

ParadoxFox
ParadoxFox

Reputation: 153

You can now use replaceChildren() to accomplish this:

root.replaceChildren();

Upvotes: 4

Taha Paksu
Taha Paksu

Reputation: 15616

If you are using jQuery, why don't you use its 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 JavaScript, you can use:

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

Upvotes: 70

Sean H. Worthington
Sean H. Worthington

Reputation: 1891

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

Upvotes: 38

What about?

    var ul = root;
    ul.innerHTML = '';

Upvotes: 10

Sampson
Sampson

Reputation: 268334

You appear to be trying this with raw JavaScript:

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

jQuery will only slow you down here.

Upvotes: 45

wheresrhys
wheresrhys

Reputation: 23500

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.

var lis = root.getElementsByTagName("li");

for(var i = 0, il = lis.length;i<il;i++) {
    root.removeChild(lis[i]);
}

Upvotes: 1

thecodeparadox
thecodeparadox

Reputation: 87073

$('#button').on('click', function() {
    $(root).empty();
});

Upvotes: 3

Related Questions