šŸ“• Build AI Agents using LangGraph.js is now out!

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.

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js

šŸ“– Build a full trivia game app with LangChain

Learn by doing with this FREE ebook! This 35-page guide walks you through every step of building your first fully functional AI-powered app using JavaScript and LangChain.js


4 Replies

Leave a Reply

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