Element.classList.toggle()

js_bits_bill

JS Bits Bill

Posted on July 27, 2020

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!

💖 💪 🙅 🚩
js_bits_bill
JS Bits Bill

Posted on July 27, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related