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
Release: 2024-12-06 10:11:12
Original
1004 people have browsed it

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);
Copy after login

Alternatively:

$(selector).hasClass(className);
Copy after login

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>
Copy after login

The following code snippet would evaluate to true:

$('span').hasClass('foo bar')
Copy after login

However, the following would return false:

$('span').hasClass('bar foo')
$('span').hasClass('foo  bar')
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template