Alexander Dickson

Manipulating classes with JavaScript

Back in the old days, classes were manipulated on elements simply with the className property. This led to an awful lot of string manipulation for manipulating the class attribute.

Thankfully, the classList property has popped up recently and is giving us all the cool stuff we love in jQuery and similar libraries.

Detecting if the browser supports classList is relatively straightforward.

var supportsClassList = ({}) == "[object DOMTokenList]";

Should you start using classList everywhere? It’s not widely supported yet, so it depends on your target platforms. For most people, they will be supporting browsers that have not yet implemented classList, but luckily fallbacks are simple to implement.


var getClasses = function(element) {
   return element.className.split(/\s+/);

Note that this won’t return a DOMTokenList, but an Array. This is generally OK as a DOMTokenList is an array-like object (that is, it provides numeric access to its properties and has a length property).


var containsClass = function(element, className) {
   return (" " + element.className + " ").indexOf(" " + className + " ") > -1;


var addClass = function(element, className) {
    return containsClass(element, className) ? false : (element.className += " " + className);

Note that this has a dependency on the method defined above.


var removeClass = function(element, className) {
    return element.className = (" " + element.className + " ").replace(" " + className + " ", " ");


var toggleClass = function(element, className) {
    return (containsClass(element, className) ? removeClass : addClass)(element, className);

Note that this has a dependency on methods defined above.

That wheel is round already

Now that you know how you can create fallbacks, it’d be a good idea to use a tried and tested shim for classList. The MDN documentation provides a good example.

Want to discuss this post? Just mention me @alexdickson.