jQuery hasClass() Method

jQuery | hasClass() Method: Learn about the jQuery hasClass() Method with its usages, syntax, and examples.
Submitted by Pratishtha Saxena, on October 16, 2022

hasClass() Method

Generally, a CSS class is declared when the HTML of the page is written down. At that time only the classes are specified for the elements. During that time a lot of CSS classes are declared for an element. It can be very hectic to remember which element contains which class. Hence, there should be a way through which we can get to know the classes that an element consists of. This can be achieved by using jQuery's method – hasClass().

The hasClass() method in jQuery helps to know whether the element consists of a particular class or not. It returns true or false for the same. Therefore, this method does not affect the predefined classes, it just tells whether there is a specified class or not. Using this method, we cannot remove the attributes of the classes.

hasClass() Method Syntax


This method takes in only a single parameter i.e., the class name. The class, here, is a CSS class. If the class, that is specified, is present in the element, it returns – true. Otherwise, it returns – false.

The below example shows the implementation of this method. We can check whether the class is there or not when the button is clicked.

jQuery hasClass() Method Example

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
      height: 200px;
      width: 300px;
    <h2>jQuery - HasClass</h2>
    <p>Click the button to check whether the element contains the specified class or not.</p>
    <img class="size" id="myImg" src="https://media.istockphoto.com/photos/mountain-landscape-picture-id517188688?k=20&m=517188688&s=612x612&w=0&h=i38qBm2P-6V4vZVEaMy_TaTEaoCMkYhvLCysE7yJQ5Q=">
    <h3 style="color:crimson ;"></h3>
  <script type="text/javascript">
            var elementClass = $('img').hasClass('size');
            if (elementClass){
                $('h3').html('It contains the specified class.')    
                $('h3').html('It does not contains the specified class.')


Example 1: jQuery hasClass() Method

All jQuery Examples

Comments and Discussions!

Load comments ↻

Copyright © 2024 www.includehelp.com. All rights reserved.