Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery how to check if the class name contains a certain value

Tags:

jquery

string

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?

like image 237
tvgemert Avatar asked Nov 23 '09 15:11

tvgemert


2 Answers

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()

like image 152
nicholaides Avatar answered Oct 03 '22 18:10

nicholaides


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.

like image 34
fyjham Avatar answered Oct 03 '22 19:10

fyjham