Show your class

jQuery is great, no doubt. Using the famous JavaScript library copious adjustments of elements can be done with ease. Especially the manipulation of classes is a snap. While it requires multiple lines to toggle the class of an element with pure JavaScript, jQuery only needs a single one. But sometimes it might be a little bit over the top to utilize a whole library for just a single task. Beneath a bunch of other useful stuff HTML5 can also bear a helping hand here. A relatively new feature called classList API enables to add, remove and toggle classes with just a single line of code.

To add a class named error to an element whose ID is box:

To remove the same class:

To toogle a class called visible write:

Besides that the classList API also provides means to check if a certain class is present:

It checks if the element with the ID box has a class called red applied and returns true or false.

The support within modern browsers is pretty good, with Internet Explorer beeing the only family that can’t deal with it so far. Luckily there is a polyfil that adds this functionality to unsupported browsers (unfortunately only starting from IE8) .


First we have an element with the already familiar ID box:
<div class="box">This is a simple box</div>

This element has some declarations applied:

#box {
	width: 200px;
	height: 200px;
	border: 1px solid;
	padding: 10px;

Additionaly there is another rule with the (non-semantic but very descriptive) classname red.

.red {
	background: red;

To add this class to the element a simple link with an onclick event-hadler is used:

<a href="#" onclick="document.getElementById('box').classList.add('red')">Add color</a>

A second link removes the red background:

<a href="#" onclick="document.getElementById('box').classList.remove('red')">Add color</a>

If you want to summarize this functionality into one link use toggle:

<a href="#" onclick="document.getElementById('box').classList.toggle('red')">Toggle color</a>

Like you can see the classList API enables us to easily deal with classes – as long as an ID is present to address the element. If not it’s still necessary to rely on jQuery or dig a little deeper into pure JavaScript. The excellent resource brought my attention to this very useful API.