šŸŽ Checkout my Learn React by Making a Game course and get 1 month Free on Skillshare!

Remove a CSS class from all elements in Javascript

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:
Remove a CSS class from all elements in Javascript

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.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.

šŸ“– 50 Javascript, React and NextJs Projects

Learn by doing with this FREE ebook! Not sure what to build? Dive in with 50 projects with project briefs and wireframes! Choose from 8 project categories and get started right away.


4 Replies

Leave a Reply

Your email address will not be published. Required fields are marked *