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:
-
Quite often you achieve altering a specific HTML element's look and feel by assigning it to a particular class, that class already possessing some customise ...
-
To iterate though a web form's contents using jQuery is as easy as 123. First, make use of the $(':input') selector and force it to grab the contents of a p ...
-
Firefox has a nasty habit of returning element background colors and colors in general in the format rgb(xxx,yyy,zzz) as opposed to the normal #xxyyzz ...
-
To return the number of checked or ticked checkboxes on a page using jQuery is in actual fact pretty simple. By making use of the special :checked select ...
-
The question for today is how to bind a single function to multiple different elements (in other words, elements with either different classes or IDs) in a ...