How to Remove All Elements with a Specific Class in JavaScript
A common task in dynamic web development is to remove a group of elements from the DOM that share a specific CSS class. This could be for clearing a list of error messages, deleting a set of items from a gallery, or hiding a group of UI components.
This guide will teach you the modern, robust, and recommended method for this task using document.querySelectorAll() in combination with the Element.remove() method.
The Core Method: querySelectorAll() and remove()
The best practice for removing multiple elements is a two-step process:
- Select: Get a list of all the elements you want to remove using
document.querySelectorAll(). This method is powerful because it uses a CSS selector to find elements and returns a staticNodeList. - Iterate and Remove: Loop over the
NodeListand call the.remove()method on each element.
Problem: you have multiple div elements with the class box, and you need to remove all of them from the DOM.
<div class="box">Box 1</div>
<div>A different element</div>
<div class="box">Box 2</div>
<div class="box">Box 3</div>
Solution:
// 1. Select all elements with the class "box".
// The '.' prefix in '.box' is a CSS class selector.
const elementsToRemove = document.querySelectorAll('.box');
// 2. Loop over the NodeList and remove each element.
elementsToRemove.forEach(element => {
element.remove();
});
After this code runs, only the div with the text "A different element" will remain on the page.
The Common Pitfall: Why getElementsByClassName() Can Fail
A frequent mistake is to use the older document.getElementsByClassName() method to select the elements. This method returns a live HTMLCollection, not a static NodeList.
"Live" means the collection is automatically updated as you modify the DOM. This creates a problem when you try to loop over it and remove elements at the same time.
Example of the error:
// AVOID THIS PATTERN!
const elements = document.getElementsByClassName('box'); // This is a LIVE collection
for (let i = 0; i < elements.length; i++) {
// When elements[0] is removed, the collection instantly updates.
// The element that was at index 1 moves to index 0.
// The loop then increments `i` to 1, SKIPPING the element that just moved.
elements[i].remove();
}
// This loop will only remove every other element!
Solution: Always use querySelectorAll. It returns a static NodeList, which is a snapshot of the DOM at the time of the query. It does not change while you are looping over it, making it safe for removal operations.
The Solution: A Simple Iteration
The combination of querySelectorAll and forEach is the modern and readable standard.
const elements = document.querySelectorAll('.box');
// NodeList has a forEach method, just like an array.
elements.forEach(element => {
element.remove();
});
You can also use a for...of loop, which is equally effective:
const elements = document.querySelectorAll('.box');
for (const element of elements) {
element.remove();
}
Practical Example: Clearing Notification Messages
This is a classic use case. A button that clears all currently displayed error messages on a page.
HTML:
<div class="notification error">Error: Invalid email.</div>
<div class="notification success">Success!</div>
<div class="notification error">Error: Password is too short.</div>
<button id="clear-errors-btn">Clear Errors</button>
JavaScript:
const clearButton = document.getElementById('clear-errors-btn');
clearButton.addEventListener('click', () => {
// Select only the elements that have BOTH "notification" and "error" classes.
const errorMessages = document.querySelectorAll('.notification.error');
console.log(`Found and removed ${errorMessages.length} error messages.`);
errorMessages.forEach(error => {
error.remove();
});
});
After clicking the button, only the "Success!" message will remain.
Conclusion
Removing all elements with a specific class is a simple task with modern JavaScript DOM APIs.
- The recommended best practice is to use
document.querySelectorAll()to get a static list of the elements. - Then, iterate over that list using
forEach()or afor...ofloop and call theelement.remove()method on each one. - Avoid using
getElementsByClassName()or other methods that return a liveHTMLCollectionwhen removing elements in a loop, as this can lead to unpredictable behavior.