DEV Community

JS Bits Bill
JS Bits Bill

Posted on • Edited on

1 1

Element.classList.toggle()

Here's a quick one! To add or remove a single class on an element you can use element.classList.add() and element.classList.remove():

// Add class
document.body.classList.add('overlay');

// Remove class
document.body.classList.remove('scroll);
Enter fullscreen mode Exit fullscreen mode

But did you know classList also includes a toggle method?

// Toggle class
document.body.classList.toggle('overlay');
Enter fullscreen mode Exit fullscreen mode

This works similar to jQuery's toggle() method where it's adds the supplied class if not present, otherwise it removes it. It's just one more tool to know about to help you keep your code clean! 🔨


Check out more #JSBits at my blog, jsbits-yo.com. Or follow me on Twitter!

Top comments (0)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay