Open In App

How to check an element contains a class using jQuery?

Improve
Improve
Like Article
Like
Save
Share
Report

Method 1: Using hasClass() method: The hasClass() is an inbuilt method in jQuery which check whether the elements with the specified class name exists or not. It returns a boolean value specifying whether the class exists in the element or not. This can be used to check for multiple classes.

Syntax:

$('element').hasClass('className')

Example:




<!DOCTYPE html>
<html>
      
<head>
    <title>
        How to check an element contains
        a class using jQuery?
    </title>
      
    <script src=
    </script>
</head>
  
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
      
    <b>
        How to check an element contains
        a class using jQuery?
    </b>
  
    <p class="example-class">
        This element has "example-class".
    </p>
  
    <p>Does the element have class?
        <span class="output"></span>
    </p>
  
    <button onclick="checkForClass()">
        Click to check
    </button>
      
    <!-- Script to use hasClass() method to
        check the existence of class name -->
    <script type="text/javascript">
        function checkForClass() {
            classCheck = $('p').is('.example-class');
            document.querySelector('.output').textContent
                    = classCheck;
        }
    </script>
</body>
  
</html>                    


Output:
check-class-hasClass

Method 2: Using is() method: This is similar to the above method and can be used to check more attributes if needed. The required element is selected and the class name is passed on like a CSS class selector. It returns a boolean value specifying whether the class exists in the element or not. This can be used to check for multiple classes.

Syntax:

$('element').is('.className')

Example:




<!DOCTYPE html>
<html>
      
<head>
    <title>
        How to check an element contains
        a class using jQuery?
    </title>
      
    <script src=
    </script>
</head>
  
<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
      
    <b>
        How to check an element contains
        a class using jQuery?
    </b>
  
    <p class="example-class">
        This element has "example-class".
    </p>
  
    <p>Does the element have class? 
        <span class="output"></span>
    </p>
  
    <button onclick="checkForClass()">
        Click to check
    </button>
      
    <!-- Script to use is() method to
        check the existence of class name -->
    <script type="text/javascript">
        function checkForClass() {
            classCheck = $('p').is('.example-class');
            document.querySelector('.output').textContent
                    = classCheck;
        }
    </script>
</body>
  
</html>                    


Output:
check-class-is



Last Updated : 23 Apr, 2019
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads