In order to remove a CSS class from all the HTML elements we can use a mix of the Javascript methods querySelectorAll() and classList.remove().
Let’s say we want to build the following Javascript example:

Basically, our app will have two functionalities:
- removing a CSS class from all elements on the page
- removing a CSS class just from all children of a given element
If you want to skip ahead here is the full code of this app and here is the live example.
Let’s start with the HTML setup:
<div>
Lorem ipsum dolor sit
<span class="red">Temporibus</span>, illo id quas
magnam cum <span class="red">dignissimos</span> reiciendis.</div>
<div class="blue-container">
<h4>š¦ The blue container</h4>
<ul>
<li class="red">Item one</li>
<li>Item two</li>
<li class="red">Item three</li>
</ul>
</div>
If we want to remove the .red class from all the elements on this page we will need to add a button, that will call the Javascript function:
<button onclick="removeClassFromAllElements()">
Remove .red the š all the page
</button>
And the code of the removeClassFromAllElements() function:
const removeClassFromAllElements = () => {
const allElements = document.querySelectorAll('*')
allElements.forEach(el => el.classList.remove('red'))
}
One nice feature of the querySelectorAll() method is that we can use it also on a particular element thus making it very easy to remove a CSS class just from a given element.
Therefore can add a new button:
<button onclick="removeClassFromOneElement()">
Remove .red the š¦ container
</button>
And here is the implementation of the removeClassFromOneElement() function:
const removeClassFromOneElement = (target) => {
target = target || document.querySelector('.blue-container')
const allElements = target.querySelectorAll('*')
allElements.forEach(el => el.classList.remove('red'))
}
That’s it! You can see the GitHub repo for this example.
PS: speaking of querySelectorAll() I’ve also written this article about how to use querySelectorAll() with wildcards. Go check it out.
š Neural Networks from Scratch - Presale
I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!
š Neural Networks from Scratch - Presale
I'm writing a book about the timeless foundational concepts of neural networks for JavaScript developers. Go from if-else to weights and biases by building tiny AI models from scratch!
Thanks a lot for this!
Glad it was helpful!
Thank you for this, short, simple and useful
hey Magz, glad you like it. Please let me know if there are other questions you may have. Have a nice day!