Here's a quick one! To add or remove a single class on an element you can useelement.classList.add()
andelement.classList.remove()
:
// Add classdocument.body.classList.add('overlay');// Remove classdocument.body.classList.remove('scroll);
But did you knowclassList
also includes a toggle method?
// Toggle classdocument.body.classList.toggle('overlay');
This works similar to jQuery'stoggle()
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 onTwitter!
Top comments(0)
Subscribe
For further actions, you may consider blocking this person and/orreporting abuse