Reputation: 24602
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
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
Reputation: 318808
There are quite a few ways:
.hasClass('whatever')
.is('.whatever')
.prop('className') == 'whatever'
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
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