jquery
  1. jquery-hasclass

jQuery hasClass()

The jQuery hasClass() method is used to check if an element has a specified class. It returns a boolean value (true or false) based on whether or not the element has the class.

Syntax

$(selector).hasClass(classname)
  • selector: The element(s) to check for the specified class.
  • classname: The name of the class to check for.

Use

The hasClass() method is useful for adding conditional logic to your jQuery code based on whether or not an element has a particular class. For example, you might want to toggle a class on/off based on whether or not an element has a certain class.

Example

Consider the following HTML code:

<div id="item" class="active">This is a div.</div>

To check if the element with id="item" has the class "active" using hasClass(), we can use the following jQuery code:

if ($('#item').hasClass('active')) {
    console.log('The item is active.');
} else {
    console.log('The item is not active.');
}

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery AJAX POST Example</title>
    <!-- Include jQuery library -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>

<div id="item" class="active">This is a div.</div>

    <script>
if ($('#item').hasClass('active')) {
    console.log('The item is active.');
} else {
    console.log('The item is not active.');
}
    </script>
</body>
</html>
Try Playground

In this example, we first select the element with id="item" using the jQuery selector. We then use the hasClass() method to check if the element has the "active" class. If it does, we log a message to the console indicating that the item is active. If not, we log a different message indicating that the item is not active.

Summary

The hasClass() method is a useful jQuery method for checking whether or not an element has a specified class. It can be used to add conditional logic to your jQuery code and make your scripts more dynamic and interactive.

Published on: