Home >Web Front-end >CSS Tutorial >How Can I Check for a CSS Class on an Element Using jQuery\'s `hasClass` Method?

How Can I Check for a CSS Class on an Element Using jQuery\'s `hasClass` Method?

DDD
DDDOriginal
2024-12-06 10:11:121001browse

How Can I Check for a CSS Class on an Element Using jQuery's `hasClass` Method?

Inspecting CSS Classes with jQuery's hasClass Method

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn