Using the classList API

A drawing of a cartoon man pointing upwards

Heads up! This post was written in 2014, so it may contain information that is no longer accurate. I keep posts like this around for historical purposes and to prevent link rot, so please keep this in mind as you're reading.

— Cory

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 now!

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