If you find yourself needing to check whether or not a particular HTML element has a specific class currently assigned to it, you’ll be pleased to know that the awesome jQuery javascript library has you covered with their ever so useful .hasClass function.

This function determines whether any of the matched elements are assigned the given class, returning true if the searched for class is in fact assigned to an element – regardless of whether or not that element has more than one class assigned to it. (Remember, HTML allows elements may have more than one class assigned to them – separated by a space in HTML notation.)

An example:

<div id="mydiv" class="foo bar"></div>
$( "#mydiv" ).hasClass( "foo" ); //returns true
$( "#mydiv" ).hasClass( "quu" ); //returns false

In other words, no need for splitting an element’s class attribute and then looping through the strings just to see if a particular class exists any more!

a lady with class - audrey hepburn

jquery logo

Related Link: https://api.jquery.com/hasclass/