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() { var that = this; var className = that[0].className; return that.each(function() { if(typeof that[0].classList === 'undefined') { var classes = className.split(/\s/); that.data('classList', classes.join(' ')); } else { that.data('classList', that[0].classList); } }); }; })(jQuery);
Testing everything out:
<div id="test" class="one two three"></div>
$(function() { $('#test').getClassList(); alert($('#test').data('classList')); });
You can see a test below.