DOM, remove all li from ul

document.getElementById(“ulMessages”);

gets the ul, now how can I zero out all list items?


var ul = document.getElementById("ulMessages");
while((var lis = ul.getElementsByTagName("li")).length > 0) {
	ul.removeChild(lis[0]);
}

You can’t simply loop through the elements because the collection of LI’s keeps getting smaller as you go.

1 Like

Why bother with getElmementsByTagName()?

Try this.

var ul = document.getElementById("ulMessages");
while(ul.firstChild) ul.removeChild(ul.firstChild);
1 Like

And lets not forget the very un-sexy solution (I personally prefer Kravvitz solutoin)


var ul = document.getElementById("ulMessages");
ul.innerHTML = "";

you could just remove the whole ul-

var who=document.getElementById(“ulMessages”);
who.parentNode.removeChild(who);

Or if you intend to build a new list:

var who2=who.cloneNode(false);
who.parentNode.replaceChild(who2,who);

That’s what I was going to suggest. :slight_smile:

In case there are non LI elements present. Even though that would be bad html.

Yes, but whitespaces will remain. Kraavitz solution kills them too.

Sure, I guess it depends on what exactly you’re after.

Easiest is to remove the <ul> since it is invalid without at least one <li> within it anyway.

True, though the question was how to remove the child items. The scenario where your clear all the child items before adding new is pretty common. Its not like the w3c will come and and knock on your door in the middle of you doing that.

:rofl: :lol: