Sometimes, we want to remove HTML elements by class name in our JavaScript code.
In this article, we’ll look at how to remove elements by class name.
Get the Parent Node of the Element and call removeChild on it
We can get the parent node of the element and call removeChild
on each element to remove an element.
For instance, if we have the following HTML:
<div>
<p class='text'>
foo
</p>
<p class='text'>
bar
</p>
<p class='text'>
baz
</p>
</div>
Then we can write:
const text = document.querySelectorAll('.text')
for (const el of text) {
el.parentNode.removeChild(el);
}
to select all the elements with the class text
.
Then we use the for-of loop to loop through each element.
In the loop body, we get the parent node of the element with the parentNode
property.
Then we call removeChild
with the el
element to remove it.
Call the remove Method
Element objects also have the remove
method to let us remove an element.
For instance, if we have the following HTML:
<div>
<p class='text'>
foo
</p>
<p class='text'>
bar
</p>
<p class='text'>
baz
</p>
</div>
Then we can write:
const text = document.querySelectorAll('.text')
for (const el of text) {
el.remove();
}
to remove each element selected with the remove
method.
Conclusion
We can select all the elements with a given class and then remove them one by one in the for-of loop.
Each element can be removed with the remove
or removeChild
method.