This article was writt by Anthony Ricaud, French OpenWeb enthusiast.
Why you need classList
A dynamic web application usually needs visual feedback from its inner mechanism or needs to display different visual elements based on users’ actions.
To change the user interface easily, you can add/remove/edit elements through the DOM API (document.createElement
, div.removeChild
, elt.style.color
, …) but it’s easier to just update the elements’ class
attribute to change how they are displayed and styled by CSS.
Let’s take an example. Suppose you want to display a form with two modes: a basic mode, and an expert mode with extra options.
This can be done with CSS rules: each mode has its own class and set of CSS code.
#anexpertinput.basic {
display: none;
}
#anexpertinput.expert {
display: inline;
}
To dynamically change the classes of elements, you can use element.className
. However, you may want to add, remove, or toggle just one class. There used to be two ways to do this, by using a library or by writing complex code with regular expressions. There is now another way with the new HTML5 API called classList
, which is implemented in Firefox 3.6.
Let’s see how it can simplify your code and improve performance at the same time.
The classList API
Here is an example to show you what the classList API looks like:
// By default, start without a class in the div:
// Set "foo" as the class by adding it to the classList
div.classList.add('foo'); // now
// Check that the classList contains the class "foo"
div.classList.contains('foo'); // returns true
// Remove the class "foo" from the list
div.classList.remove('foo'); // now
// Check if classList contains the class "foo"
div.classList.contains('foo'); // returns false: "foo" is gone
// Check if class contains the class "foo",
// If it does, "foo" is removed, if it doesn't, it's added
div.classList.toggle('foo'); // class set to
div.classList.toggle('foo'); // class set to
Demo
Let’s go back to our initial example of a form with both a basic and an expert mode – check out the live demo to see it in action.
As you can see in the code below, you can switch between the two modes with one line of JavaScript.
Blablablablabla...
#box.expert > #help,
#box.expert > label[for="postpone"],
#box.expert > label[for="lang"] {
display: none;
}
See the Mozilla documentation and the HTML5 specification for more details on classList.
Performance
Using the classList API is not only easier, it’s also more powerful. Take a look at what we observed using Firefox 3.6.
Interoperability
Since other browser vendors have not yet implemented the HTML5 classList API, you still need fallback code. You can use this sample code as fallback.
To know more about the current implementation of classList in well-known JavaScript libraries, see:
About Paul Rouget
Paul is a Firefox developer.
16 comments