Question:
How to ascertain the presence of a CSS class on an HTML element using jQuery, particularly for usage within an if-statement condition?
Answer:
Leverage the robust hasClass method:
jQueryCollection.hasClass(className);
Alternatively:
$(selector).hasClass(className);
Implementation:
The argument for hasClass is the CSS class name as a string. It returns a boolean, enabling you to perform equality checks within your conditional statements. Notably, whitespace in the class name is matched literally.
Example Usage:
Consider the HTML element:
<span>
The following code snippet would evaluate to true:
$('span').hasClass('foo bar')
However, the following would return false:
$('span').hasClass('bar foo') $('span').hasClass('foo bar')
The above is the detailed content of How Can I Check for a CSS Class on an Element Using jQuery\'s `hasClass` Method?. For more information, please follow other related articles on the PHP Chinese website!