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>
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> ).
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").
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.
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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With