Discovering if any element has any class in jQuery

Try:

$('*').each(function() {
    if ($(this).hasClass()) {
        var class_name = $(this).attr('class');
        // do something
    }
});

Why you would want to do this, I have no idea. It is very inefficient


For what it's worth:

$(this).hasClass() 

always returns false.

$("[class]") 

doesn't work either, as it returns elements like

<p class=""> my p </p>

jsfiddle for both here: http://jsfiddle.net/JZ8LV/1/

Solution:

$(this).hasClass('') 

returns true for elements without a class, including those of the form

<p class=""> my p </p>

so

$('*').each(function() {
    if ($(this).hasClass('') === false) {
        $("body").append($(this).prop("tagName") + " has a proper class defined <br/>");
    }
});

returns all the tags with a proper class defined.

Jsfiddle: http://jsfiddle.net/2Rtj5/


You can use something like this:

$("[class]").each(function(){
   var className = $(this).attr("class");
})

Has Attribute Selector

Demo: http://jsfiddle.net/L5WAV/1/ (see results in console - two divs should be found)