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!