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?
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()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With