If you are a web developer, you surely must know how handy it is to dynamically change the class attribute on an element. The benefits this technique are quite a few:
- You leave any changes in the look and feel to the CSS
- You avoid having to loop lots of elements as you can allow CSS to do that job for you by assigning a class on a parent element
- You can trigger CSS transitions and avoid having to write your own animation
- And many more…
The issue with classes is that it is not too simple to work with because of their representation in the DOM. When you read out className
you get one string and you need to split it and use regex to find if a class was used and all kind of other annoyances. This is also why it is a very common interview questions for web developers to write a function to deal with classes.
Well, you might not be aware of it, but HTML has a very cool new way to deal with classes called classList. This makes it dead easy to add, remove, toggle and check for classes on an element – natively in your browser. You can play with it at JSFiddle:
The methods you have are all you really need:
element.classList.add('foo')
adds the classfoo
to the element (if it already exists it does nothing)element.classList.remove('foo')
removes the classfoo
from the elementelement.classList.toggle('foo')
alternatively adds and removes the classfoo
from the elementelement.classList.contains('foo')
returns if the class is applied to the element or notelement.classList.toString()
returns all the classes as a string (same as reading outclassName
)
The browser support is very good with IE being the party pooper. However, there is a polyfill by Eli Grey available for you to use.
About Chris Heilmann
Evangelist for HTML5 and open web. Let's fix this!
21 comments