Manipulating lists is a cornerstone of dynamic web pages. A common task is to remove list items (<li>) from an unordered list (<ul>), either to clear the entire list or to remove specific items based on a condition. Modern JavaScript provides several clean and efficient ways to accomplish this.
This guide will demonstrate the best methods for removing all <li> elements from a <ul> and for removing specific <li> elements that match certain criteria. We will focus on modern, readable, and safe approaches.
Removing All <li> Elements from a <ul>
This is the most straightforward task: you have a list and you want to make it empty.
For example, you have an existing list and need to clear its contents programmatically.
<ul id="my-list">
<li>First</li>
<li>Second</li>
<li>Third</li>
</ul>The Modern Method (Recommended): ul.replaceChildren()
The element.replaceChildren() method is the modern, safe, and recommended way to remove all children from an element. When called with no arguments, it simply removes everything.
Solution:
const myList = document.getElementById('my-list');
// Remove all child elements from the <ul>.
myList.replaceChildren();
console.log(myList.innerHTML); // Output: ""The Classic Method: ul.innerHTML = ''
A very common and concise way to clear an element is to set its innerHTML property to an empty string. While effective, it has some drawbacks.
Solution:
const myList = document.getElementById('my-list');
// Setting innerHTML to an empty string removes all descendants.
myList.innerHTML = '';
console.log(myList.children.length); // Output: 0Removing Specific <li> Elements from a <ul>
More often, you will need to remove only certain items from a list based on a condition, such as their content, class, or data attribute.
For example, you have a list and want to remove only the items that meet a specific criterion.
<ul id="task-list">
<li class="task">Task 1</li>
<li class="task completed">Task 2</li>
<li class="task">Task 3</li>
<li class="task completed">Task 4</li>
</ul>The Core Method: querySelectorAll and element.remove()
The best practice for this is to get a list of all the elements you want to remove and then iterate over that list, calling the modern .remove() method on each one.
Solution: this script removes all <li> elements that have the class completed.
// Get a NodeList of all <li> elements with the 'completed' class.
const completedTasks = document.querySelectorAll('#task-list li.completed');
// Loop over the NodeList and remove each element.
for (const task of completedTasks) {
task.remove();
}A Note on Removing While Iterating (The Live Collection Pitfall)
A common mistake is to use a method like getElementsByTagName or getElementsByClassName and try to remove items from the list you are looping over. These older methods return a live HTMLCollection, not a static NodeList. "Live" means the collection changes automatically as you modify the DOM.
// This will NOT work correctly!
const listItems = document.getElementsByClassName('task'); // This is a LIVE collection
for (let i = 0; i < listItems.length; i++) {
// When an item is removed, the collection's length and indices change,
// causing the loop to skip the next item.
listItems[i].remove();
}Solution: Always use querySelectorAll, which returns a static NodeList. A static list is a snapshot of the DOM at the time you made the query, so it is safe to iterate over it even as you remove elements from the actual DOM.
Practical Example: Removing Items by Index
This script demonstrates how to remove items based on their position in the list, such as removing all odd-numbered list items.
const allTasks = document.querySelectorAll('#task-list li');
// Loop through the list, checking the index of each item.
allTasks.forEach((task, index) => {
// JavaScript indices are zero-based, so odd-numbered items have an even index.
if (index % 2 === 0) { // 0, 2, 4, etc.
task.remove();
}
});Conclusion
Modern JavaScript provides clean and robust methods for removing list items from the DOM.
- To remove all
<li>elements, theul.replaceChildren()method is the safest and most modern approach. - To remove specific
<li>elements, the best practice is to get a static list withdocument.querySelectorAll(), loop over it, and call theelement.remove()method on each item that matches your condition.
Avoid older methods like getElementsByClassName when removing items in a loop to prevent issues with live collections, and prefer element.remove() over the more verbose element.parentNode.removeChild(element).