Search code examples
javascripthtml-listsremovechild

javascript remove li without removing ul?


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>

Solution

  • 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.