JS: classList, yipee!

Paul Kinlan

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");
element.classList.add("hello");

Removing a class:

var element = document.getElementById("test");
element.classList.remove("hello");

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");
element.classList.toggle("hello");

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?

Yes!

Paul Kinlan

Trying to make the web and developers better.

RSS Github Medium