Using HTML5’s ClassList API

On May 21, 2013, in Javascript, Browsers, by Anuj Gakhar

ClassList is a native and convenient alternative to accessing an element’s list of classes as a space-delimited string via element.className. It makes it easier to accomplish common tasks such as adding class, removing class etc. I find myself using the ClassList API more and more recently (as opposed to the equivalent jQuery functions) and I am happy that this is now being supported by more and more browsers. As of now, apart from IE8 and IE9, most other browsers seem to support it.

If you want to detect whether your browser supports this feature, it is pretty simple :-
[js]var hasClasslist = ("classList" in document.documentElement) ? true : false;[/js]

The classList object contains a number of helpful methods :-

  • length
  • add
  • remove
  • toggle
  • item
  • contains

Here are some of the replacements/equivalants of the jQuery functions to add/remove/toggle classNames to a DOM element :-
[js] // DOM element
var elm = document.querySelector(".myDiv");

/* Adding a class via jQuery */
$(elm).addClass("className");

/* classList equivalent */
elm.classList.add("className");

/* Removing a class via jQuery */
$(elm).removeClass("className");

/* classList equivalent */
elm.classList.remove("className");

/* check whether element has class via jQuery */
if($(elm).hasClass("className"))

/* classList equivalent */
if(elm.classList.contains("className"))

/* toggle class via jQuery */
$(elm).toggleClass(‘className’)

/* classList equivalant */
elm.classList.toggle(‘className’)[/js]

You can start using classList today, although it won’t work in IE 9 or below. To fix that, there is an excellent cross browser Javascript shim available that fully implements element.classlist.

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

© 2011 Anuj Gakhar
%d bloggers like this: