jQuery: cross-browser DOM classList

The HTML5 specifications introduce the concept of DOM classList to be used with any HTML element. According to the specifications, this DOM property should contain a list of tokens which represent the various class names used within the class attribute. Simply put, this property returns a space-separated string containing all the class names attached to a given element. Some browsers already implement classList, others don't. For that reason, we need to create a simple jQuery plugin to handle this property in a cross-browser fashion. Let's see how.

We need to check whether this property exists in the DOM of a web browser by comparing its value with undefined. If so, we split the className property of the element into an array and we attach a classList variable to the element using the data() method. This variable will contain the string version of the array, space-separated. On the contrary, if a browser supports classList, we use its value with our data() method:


(function ($) {

    $.fn.getClassList = function () {



        return this.each(function () {
            var that = $(this);
            var className = that[0].className;

            if (typeof that[0].classList === 'undefined') {

                var classes = className.split(/\s/);

                that.data('classList', classes.join(' '));


            } else {

                that.data('classList', Array.prototype.join.call(that[0].classList, ' '));

            }

        });

    };


})(jQuery);

Testing everything out:


$(function () {

    $('#test').getClassList();

    console.log($('#test').data('classList')); // one two three

});

[view-example url="http://jsfiddle.net/gabrieleromanato/Kvmj2/"]
Back to top