Using the classList API

jQuery makes it easy to add, remove, and toggle classes on various elements. It's too bad this stuff wasn't built into JavaScript. But wait—it is!

What your looking for didn't exist until IE10, but it's been in Firefox, Chrome, Safari, and Opera for some time now. It's called the classList API, and it makes working with classes a breeze, even without a library.

For these examples, assume that el is a reference to an element on your page.

// Adding a class
el.classList.add('your-class-name');

// Removing a class
el.classList.remove('some-class-name');

// Toggling a class on/off
el.classList.toggle('some-class-name');

// Checking for a class
if( el.classList.contains('some-class-name') ) {
    // has the class
} else {
    // doesn't have the class
}

This is just as easy as any library out there, and you can use it today if you're not worried about IE9 and below. (Actually, you can still use it with a shim.)

Author avatar

About the author

New Hampshirite building web apps in Florida. Creator of Surreal CMS, Postleaf, and DirtyMarkup.

Need to get in touch? Catch me on Twitter.