JS: classList, yipee!

I remember the first time I used jQuery and probably the biggest thing that impressed me (by the way I am pretty much a nerd++) was not the compress syntax, the ability to do XHR, or live events (ok, live events came a lot later, and I used them all over the place on http://www.frienddeck.com) it was the ability to quickly manipulate the class attribute.

For a long time I have been using the class attribute to hold state, but also naturally to providing styling. I had my own routines to parse and manipulate the class attribute. However, it never felt natural – I don't know why, it just didn't. Then in jQuery this all came as standard – we now had the ability to 'toggle' a class (my routines never had this….. not sure how I missed it to be honest) using simple semantics.

Put simply. Sweet!

Now, there is an API built into the browser to help developers interact with the 'class' attribute. The API provides a lot of what I saw in jQuery – toggle (to turn a class on or off), add and remove, and 'contains' to check the presence of a class in a classList. Its an awesome practical example of the standards bodies (or spec writers) listening to and recognising the needs of Developers.

What is a classList?

Under the hood it is a specialised collection provided by the DOM called DOMTokenList. With this interface you can manipulate the class attribute without having to resort to yucky string manipulation.

Examples? It is a pretty simple API, so it should be straight forward – however here goes:

Adding a class:

var element = document.getElementById("test");

Removing a class:

var element = document.getElementById("test");

Toggling a class. If the class is on the element, it will be removed. If it is not, it will be added:

var element = document.getElementById("test");

Checking for presence a class:

var element = document.getElementById("test");
if(element.classList.contains("hello")) { ... }

I have a better demo that I will blog about in a couple of days.

Browser support?

Well at the moment, Firefox 3.6+ and Chrome 7+. (Not sure about Opera )

Is this Awesome?


I lead the Chrome Developer Relations team at Google.

We want people to have the best experience possible on the web without having to install a native app or produce content in a walled garden.

Our team tries to make it easier for developers to build on the web by supporting every Chrome release, creating great content to support developers on web.dev, contributing to MDN, helping to improve browser compatibility, and some of the best developer tools like Lighthouse, Workbox, Squoosh to name just a few.

I love to learn about what you are building, and how I can help with Chrome or Web development in general, so if you want to chat with me directly, please feel free to book a consultation.

I'm trialing a newsletter, you can subscribe below (thank you!)