JS Bits with Bill
JS Bits with Bill

JS Bits with Bill

Element.classList.toggle()

Element.classList.toggle()

JS Bits with Bill's photo
JS Bits with Bill

Published on Jul 27, 2020

1 min read

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);

But did you know classList also includes a toggle method?

// Toggle class
document.body.classList.toggle('overlay');

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!

 
Share this