tags:

views:

912

answers:

2

I would like to read out the classnames attached to a certain element and take action based on that the classname contains a certain value ("active"). The classname could be something like: class="bla-bla-bla first active". What is the best way to do that?

+11  A: 

Class names are separated by spaces, so you just need $(something).hasClass('active')

Additionally, you could use the .is() method, like this: $(somthing).is('.active'), which returns true or false.

Finally, you might be better off using it as the selector, like so: $('li.active').doSomething()

nicholaides
Thanks, needed the push in the right direction!
tvgemert
+5  A: 

You'd simply use the .is function. For example if you had a div <div id="divid" class="bla-bla-bla first active" /> you could use:

if ($('#divid').is('.active')) { alert('Its active!'); }

This method will work with any jQuery selector syntax meaning you can do some pretty in-depth checks with this far beyond just css class. See the jQuery documentation for more info.

Tim Schneider