classList: easily manipulate CSS classes with plain JavaScript

You might already know you can change the class of an element with the className property:


var title = document.getElementById( 'title' );
title.className = 'active';

But what if you also wanted to add another class name to the class attribute? What if you wanted to add, for example, 'animated', without knowing a priori which classes are there already? You could just append to the existing value:


title.className += ' animated';

and pray that 'animated' wasn't already there. And what if you want to remove it? You'll have to be manipulating a string too. This is too much of a hassle, and probably one of the reasons why people prefer using JavaScript frameworks, jQuery style.

But there's a better, faster, native way! Allow me to introduce... classList! It is a property available in every element in a page, just as className is too.

Let's do the same we did above, but using classList:


var title = document.getElementById( 'title' );

// Add class
title.classList.add( 'active' );

// Add it if doesn't exist yet, remove it if present
title.classList.toggle( 'animated' );

// Remove class
title.classList.remove( 'animated' );

Apparently support for classList was introduced in Chrome 8 and Firefox 3.6, that is, about two years ago. So I guess you can count on this working in most browsers out there. If you aren't happy with that assumption, there's a shim on the Mozilla entry on classList, just in case you expect someone to use a superoutdated browser with your code.

I found about this nifty new DOM property as recently as two days ago, while perusing the Vanilla JS FTW site, and I instantly labeled it as great! I also thought I was probably the last one to learn about it, but as I asked some fellow developers and no one had heard about it, I decided I should share it with the world!