jQuery: Iterate Through an Element’s Classes Programming 28 DEC 2010

More often than not, your HTML elements will have more than one class assigned to them. Now while it is easy to check if an element belongs to a certain class with jQuery’s built in hasClass function, you’ll be pleased to know it is just as easy to iterate through all of an element’s classes with some basic loop work.

How basic you ask? Well actually a single simple for loop really.

Taking into account that a class is nothing more than an attribute, we can retrieve an element’s assigned classed with a simple


The result is a single string value containing the classes currently attached to the element. To iterate through the classes, we simply break up the returned string with the split function:

var classList = $('#myelement').attr('class').split(/\s+/);

Now that we have an usable array, we simply loop through it in any accepted manner, leaving us with code that looks like this:

var classList = $(this).attr('class').split(/\s+/);
               for (i = 0; i < classList.length; i++) {
                   if(classList[i].length > 0){


Related Posts:

About Craig Lotter

South African software architect and developer at Touchwork. Husband to a cupcake baker and father to two little girls. I don't have time for myself any more.

  • Another nifty trick is that you can use the jQuery each() function to iterate over the class names…

    var classList = $(‘#myElement’).attr(“class”).split(/s+/);
    $.each(classList, function(index, className) {
        if (className.length) {        alert(className);    }

  • Paul

    Missing a backslash in your regular expression. Should be /s+/ instead of /s+/.