Alan2
Alan2

Reputation: 24602

Is there a way in jQuery to determine if an element has a class?

I have used the following to determine if an element is hidden:

if ($("#sidebar").is(':hidden')) {

Is there some way I could determine if #sidebar has the class "black" instead of checking if it is hidden?

Upvotes: 3

Views: 245

Answers (6)

Bojangles
Bojangles

Reputation: 101553

You can either use .hasClass('black'):

if($('#sidebar').hasClass('black');

Or, you can use .is() for greater flexibility:

if($('#sidebar').is('.black');

.is() allows you to filter the element using the various other selectors that jQuery offers. Do note that .hasClass() is faster, however, as this answer states.

Upvotes: 4

ThiefMaster
ThiefMaster

Reputation: 318808

There are quite a few ways:

All of them have their own advantages and disadvantages:

  • hasClass: Usually the best choice, checks if the element has the given class no matter if it has other classes, too.
  • is: checks for a selector. Slower than hasClass as it invokes the selector engine, besides that not really different. More flexible since you can mix it with other selectors instad of just checking the class if you ever need it.
  • className: Checks if the element has exactly only the given class. Usually not what you want, but mentioned since it is a way.

Upvotes: 6

coolguy
coolguy

Reputation: 7954

if ($("#sidebar").hasClass('black')) {

Upvotes: 4

xdazz
xdazz

Reputation: 160973

if ($("#sidebar").hasClass('black')) {

The doc.

Upvotes: 3

antyrat
antyrat

Reputation: 27765

if($("#sidebar").hasClass('black'))

Upvotes: 3

Tats_innit
Tats_innit

Reputation: 34117

Api : .hasClass('black') will do the trick for you Working Demo http://jsfiddle.net/xvA8d/2/

Link: http://api.jquery.com/hasClass/

Determine whether any of the matched elements are assigned the given class.

Upvotes: 9

Related Questions