Last updated: Mar 5, 2024
Reading time·2 min
To remove all elements with a specific class:
document.querySelectorAll()
method to select the elements by class.forEach()
method to iterate over the collection.remove()
method on each element to remove it from the DOM.Here is the HTML for the examples.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <title>bobbyhadz.com</title> </head> <body> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const boxes = document.querySelectorAll('.box'); boxes.forEach(box => { box.remove(); });
We used the document.querySelectorAll()
method to select all of the elements with a class of box
in the DOM.
The querySelectorAll
method returns a NodeList
, so we are able to use the
NodeList.forEach()
method to iterate over the collection of elements.
If you use the
document.getElementsByClassName()
method, you have to convert the result to an array before calling the
forEach()
method.
const boxes = Array.from(document.getElementsByClassName('box')); boxes.forEach(box => { box.remove(); });
Notice that the querySelectorAll()
method takes a selector as a parameter. In
the call to the method, we prefixed the class name with a dot .box
.
const boxes = document.querySelectorAll('.box'); boxes.forEach(box => { box.remove(); });
Whereas the getElementsByClassName()
method takes the class name as a
parameter.
The function we passed to the forEach()
method gets called with each element
in the collection.
On each iteration, we used the Element.remove() method to remove the element from the DOM.
If you need to remove the elements with a specific class name without removing
their children, use the replaceWith()
method.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box"> <span>Child 1</span> </div> <div class="box"> <span>Child 2</span> </div> <div class="box"> <span>Child 3</span> </div> <script src="index.js"></script> </body> </html>
And here is the related JavaScript code.
const boxes = document.querySelectorAll('.box'); boxes.forEach(box => { box.replaceWith(...box.childNodes); });
To remove an element without removing its children, we had to replace the element with its children.
The childNodes property returns a
NodeList
containing the child elements, text and comments.
The replaceWith()
method takes multiple, comma-separated elements with which
to replace the element it was called on, so we had to use the spread syntax
(...) to unpack the values from the NodeList
in the call to the method.
You can learn more about the related topics by checking out the following tutorials: