Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Discovering if any element has any class in jQuery

I have inherited some jQuery and HTML and need to find out if any of the HTML elements have a class name of any value. I've read around a few threads and Googled but can't find anything useful. So in pseudo-code what I'd like is:

Loop through all HTML elements

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

Hoping that makes sense!

like image 707
Kev Avatar asked Jan 31 '13 17:01

Kev


People also ask

How do you check if an element contains a class in jQuery?

jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".

What does $() do in jQuery?

When a jQuery object is passed to the $() function, a clone of the object is created. This new jQuery object references the same DOM elements as the initial one.

How check class is active or not in jQuery?

Method 1: Using hasClass() method: The hasClass() is an inbuilt method in jQuery which check whether the elements with the specified class name exists or not.


1 Answers

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

like image 128
jacktheripper Avatar answered Oct 12 '22 02:10

jacktheripper