Skip to main content
Header image by Kelly Sikkema © Kelly Sikkema

How to Add or Remove a Class Using Toggle Depending on a Condition in JavaScript

The secret parameter you didn’t know about classList.toggle() that will simplify your life.

Introduction #

I’m pretty sure you already worked on a project where you had to add or remove a class, and it has been done with an if-else statement; in the if statement, you add the class, and in the else, you remove it. Please don’t lie; I know you already see that 😁

The good news, you can drastically simplify it using the method toggle from the classList. Almost everyone thinks about the toggleClass from jQuery that… toggle a class 😅 If the class isn’t present, it will add it; if not, it will remove it. But the vanilla one can act differently using the second parameter. It allows you to pass a boolean that will add the class if it’s true and remove it if it’s false.

Example #

Imagine you have the following code:

const element = document.querySelector('.element')
const showElement = true // Change it to fit your needs

if (showElement) {
  element.classList.add('visible')
} else {
  element.classList.remove('visible')
}

This is fine, and it works well, but you can simplify it using the toggle method:

const element = document.querySelector('.element')
const showElement = true

element.classList.toggle('visible', showElement)

This will work the same way as the previous code 🎉
Pretty neat, right?

Conclusion #

You learned a new way to use the toggle method and simplify your code.
I hope you learned something new and can be helpful in your following projects!

Tags

See Also

No results...