2

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?

4
  • Try and see, why shouldn't it work? Commented Jul 2, 2013 at 10:11
  • I vote to close "unclear what you're asking" just because there is no "OP is too lazy to test"... ;) Commented Jul 2, 2013 at 10:16
  • 1
    if you have multiple .myclass this will return true as long as one of them has .bar Commented Jul 2, 2013 at 10:20
  • ya it's easy to test, but googling this answer was even less work. +1 Commented Nov 29, 2016 at 20:09

6 Answers 6

11

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'))
Sign up to request clarification or add additional context in comments.

Comments

9

Or skip the check and just select the elements instead.

$('.myclass.bar')

If you need to check for existence:

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

Comments

2

Yes it works

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

}

Comments

1

you can try like this

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

hope this helps you

1 Comment

will always be true. You need to check length
1

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') ) {
  // ...
}

Comments

0

Yes it will work

Read more about jquery selectors

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.