Removing `li` elements from a list with JavaScript
April 28, 2021 ‐ 2 min read
Without having to reach for jQuery, Vue, React or another fancy library you can easily remove the contents of a HTML list with just plain JavaScript. Lets assume that we have the following list in HTML.
<ul id="example">
<li>...</li>
<li>...</li>
</ul>
There is a couple ways we can go about removing the li
elements, but we need to start with a selector to store our list in a variable. Since the list has the ID example
we can use that to find the list in the DOM.
const list = document.getElementById("example");
Maybe the easiest way to empty the list is by setting its innerHTML. This will erase all the contents of the list.
list.innerHTML = "";
This will leave you with an empty list, as follows:
<ul id="example"></ul>
While effective, this approach is somewhat rigorous too. As mentioned before, it will erase all the contents of the list. So if you had something else in your list, like a div
for example, it is removed as well.
Of course there is a way to just remove the li
elements too. With a for
loop we can remove just remove the li
elements. We use a different selector here to get all the li
's of the list instead of the list itself.
var listElements = document.querySelectorAll("#example li");
for (var i = 0; (li = listElements[i]); i++) {
li.parentNode.removeChild(li);
}