Detecting if any element has any class in jQuery

I inherited some jQuery and HTML and have to figure out if any of the HTML elements have a class name of any value. I have read several threads and Googled but cannot find anything useful. So in pseudocode, I want:

Loop through all HTML elements

If any of them have any class at all:
    Get their class name as a string

      

Hope this makes sense!

+3


source to share


6 answers


Try:

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

      



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

+10


source


What is it worth for:

$(this).hasClass() 

      

always returns false.

$("[class]") 

      

doesn't work either as it returns items like

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

      

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

Decision



$(this).hasClass('') 

      

returns true for elements without a class, including forms

<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 tags with the corresponding class .

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

+10


source


You can use something like this:

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

      

has an attribute selector

Demo: http://jsfiddle.net/L5WAV/1/ (see results in console - need to find two divs)

+6


source


var classObj = {};

$('*').each(function(){
    var cNames = this.className.split(' ');
    for(var i=0, l=cNames.length; i<l; i+=1){
        classObj[cNames[i]] = true;
    }
});

      

This will give you an object ( classObj

) with every seeming document class as a property, so the class name will not appear multiple times if there are elements with the same class in the document. I really wouldn't do it or see a use case in it.

+1


source


To get all elements with a class, you can use $('*[class]')

:

$('*[class]').each(function(){
    // do what you want
});

      

You can even easily count them with $('*[class]').length

.

+1


source


Not a direct question, but I need it, so it's appropriate for future users.

If you want to find if any element has a specific class, you can use this function:

function find_any_element(className) {
    var found = false;
    $('*').each(function() {
        if ($(this).hasClass(className)) {
            var class_name = $(this).attr('class');
            alert("There is an element with this class: " + class_name);
            found = true;
        }
    });
    if(!found) {
        alert("No element with className '" + className + "' found.");
    }
}

      

0


source







All Articles