jQuery: Iterate Through an Element’s Classes

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

$('#myelement').attr('class');

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){
                       alert(classList[i]);
                   }
               }

Nifty.

You might also enjoy:

About Craig Lotter

Craig Lotter is an established web developer and application programmer, with strong creative urges (which keep bursting out at the most inopportune moments) and a seemingly insatiable need to love all things animated. Living in the beautiful coastal town of Gordon's Bay in South Africa, he games, develops, takes in animated fare, trains under the Funakoshi karate style and for the most part, simply enjoys life with his amazing wife and daughter. Oh, and he draws ever now and then too.
This entry was posted in Tutorials, jQuery and tagged , , , , . Bookmark the permalink.
    blog comments powered by Disqus