Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

JS Bits Bill
JS Bits Bill

Posted on • Edited on

     

Element.classList.toggle()

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);
Enter fullscreen modeExit fullscreen mode

But did you knowclassList also includes a toggle method?

// Toggle classdocument.body.classList.toggle('overlay');
Enter fullscreen modeExit fullscreen mode

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
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

3rd Party JS Developer, Blogger, and Competitive Olive Eater
  • Location
    Austin, TX
  • Joined

More fromJS Bits Bill

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp