Quick Tip – HTML5 classList Element Property
When we want to change the style or display of an HTML element most of the time we update its class name. The main way to change the class name is using the element’s className property. This raises a little problem. The className property is string based and can get a string value of one or more classes. When we want to toggle/update a class name and we have more than one class set to an element that means we will have to do string manipulation. String manipulations can be cumbersome and can affect the performance of the operation.
Not anymore… HTML5 introduces the classList property for HTML elements and it can help to avoid the string manipulation problem.
The classList Property
Each HTML element holds a new classList property. The classList holds an instance of DOMTokenList,which is a new list type that includes a set of space-separated tokens. The DOMTokenList has the following API:
- length – a property for the length of the list.
- item(index) – a function that returns the list item that exists in the given index.
- contains(token) – a function that returns true if the list contains the given token. Else it returns false.
- add(token) – a function to add a given new token to the list.
- remove(token) – a function to remove a given token from the list.
- toggle(token) – a function that adds the token to the list if it doesn’t exist. If the token exists it is removed from the list.
The classList property is read-only and in order to manipulate it you must use the previous DOMTokenList API.
Here are some examples of using the classList property and the DOMTokenList API:
// Adds a red class to a div element div.classList.add("red"); // Removes a blue class from a div element div.classList.remove("blue"); // If the visible class is set on the element it will be removed. // Else the visible class will be added to the div div.classList.toggle("visible"); // Will output to the console 'true' if the visible class exists. // Else it will output 'false' console.log(div.classList.contains("visible")); classList Support in Browsers
As in all HTML5 new features, not all the browsers support the classList property. To see if you can use the classList property, you can visit the can I use website.
HTML5 classList property can help you avoid string manipulations on the className property. It is using a new list type, the DOMTokenList, in order to expose its functionality.
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)