Hidden Gems of HTML5: classList

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 class foo to the element (if it already exists it does nothing)
  • element.classList.remove('foo') removes the class foo from the element
  • element.classList.toggle('foo') alternatively adds and removes the class foo from the element
  • element.classList.contains('foo') returns if the class is applied to the element or not
  • element.classList.toString() returns all the classes as a string (same as reading out className)

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.

View full post on Mozilla Hacks – the Web developer blog

VN:F [1.9.22_1171]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.22_1171]
Rating: 0 (from 0 votes)