Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 904
MAZUMA Avatar asked Sep 13 '13 20:09

MAZUMA


People also ask

Does Li need to be in UL?

The <li> HTML element is used to represent an item in a list. It must be contained in a parent element: an ordered list ( <ol> ), an unordered list ( <ul> ), or a menu ( <menu> ).

How do I delete all Li in UL?

To remove all li elements from a ul element with JavaScript, we can set the innerHTML property of the ul element to an empty string. Then we write: document. getElementById("root").

How do I add Li to UL?

To add new li to ul on click with JavaScript, we can call the appendChild method. const ul = document. getElementById("list"); const li = document. createElement("li"); li.


2 Answers

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.

like image 69
Justin Wood Avatar answered Sep 24 '22 03:09

Justin Wood


This should do the trick:

var lis = document.querySelectorAll('#myList li');
for(var i=0; li=lis[i]; i++) {
    li.parentNode.removeChild(li);
}

Demo http://jsfiddle.net/krasimir/UhhuX/

like image 17
Krasimir Avatar answered Sep 22 '22 03:09

Krasimir