jQuery - can you check to see if a class has another class?

12,815

Solution 1

This is trivial to test. See it working on jsFiddle (a great online tool for web developers).

<div id="mydiv" class="myclass bar">
</div>

jQuery:

alert($('.myclass').hasClass('bar'))

Solution 2

Or skip the check and just select the elements instead.

$('.myclass.bar')

If you need to check for existence:

$('.myclass.bar').length > 0

Solution 3

Yes it works

if ($('.myclass').hasClass('bar')) {
//do some thing 

}

Solution 4

you can try like this

if($('.myclass').find('bar').length > 0)
   //Do you code

hope this helps you

Solution 5

A class cannot have another class, only an element (that you get with its selector) can have multiple classes.

In order to check if #mydiv which has the class bar also has the class foo you can write something like:

if( $('#mydiv.bar').hasClass('foo') ) {
  // ...
}
Share:
12,815
user-a5567ffg
Author by

user-a5567ffg

Updated on June 05, 2022

Comments

  • user-a5567ffg
    user-a5567ffg almost 2 years

    I know that you can check to see if an id (or other selector) has a certain class:

    $('#mydiv').hasClass('bar')
    

    But can you check to see if a class also has another class? Like:

    $('.myclass').hasClass('bar')
    

    Just wondering?