A Beautiful Site

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

// Removing a class

// Toggling a class on/off

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