javascript remove li without removing ul?

MAZUMA picture MAZUMA · Sep 13, 2013 · Viewed 60.1k times · Source

Is there any way to remove the li elements of a ul without also removing the ul? I can only seem to find this.

var element = document.getElementById('myList');
element.parentNode.removeChild(element);

But, this removes the ul. I'm hoping to be able to remove and append li elements on the fly without also having to createElement the ul every time I remove li elements. Just looking for a simpler way. Thanks for any help.

<div id="listView">
  <ul id="myList" class="myList-class">
    <li>item 1</li>
    <li>item 2</li>
  </ul>
</div>

Answer

Justin Wood picture Justin Wood · Sep 13, 2013

You can do something like this.

var myList = document.getElementById('myList');
myList.innerHTML = '';

If you are using jQuery

$('#myList').empty();

Both of these will remove EVERYTHING inside the list.