How to Check if element has class in JavaScript

CSS classes are very helpful when need to add same style on multiple HTML elements. However, classes are not limited to styling alone; they also enable us to perform various actions based on the presence or absence on an element.

In this tutorial, I show how you can check specific class on single or multiple elements using JavaScript with examples.

How to Check if element has class in JavaScript


Table of Content

  1. Check a single element has class using JavaScript
  2. Check multiple elements has class using JavaScript
  3. Conclusion

1. Check a single element has class using JavaScript

To check whether a specific class exists on a single HTML element using JavaScript, we can utilize the powerful classList property. This property has contains() method, which allows us to determine if a class is present on the element or not.

Example:

HTML

  • Create a <div> element with the class "red" is created and assigned the ID "divel".
  • Create a a button with the label “Has class – red”, and an onclick attribute is set to call the hasClass() function. This function checks for the presence of the class "red" on the <div> element with the ID "divel".
  • The result of the class check is displayed in a <div> with the ID "result1".

JavaScript

  • Create hasClass() function, which takes two parameters:
    1. The element instance on which the class needs to be checked.
    2. The class name that needs to be found.
  • Within the hasClass() function, the classList.contains() method is used to search for the specified class on the element. This method returns a boolean value (true if the class is present, false otherwise).
  • If the classList.contains() method returns true, the message “True” is displayed in the <div id="result1">. Otherwise, if it returns false, the message “False” is displayed.
<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8">
   <meta name="viewport" content="width=device-width, initial-scale=1">
   <title>How to Check if element has class in JavaScript</title>
</head>
<body>
   <style>
   .content{
      width: 100px;
      height: 100px;
      color: white;
   }

   .red{
      background: red;
   }
   </style>

   <h2>Search class on single element</h2>
   <div class='content red' id='divel' ></div>

   <br><br>
   <input type='button' value="Has class - red" onclick="hasClass(document.getElementById('divel'),'red')">

   <br><br>
   <b>Result : </b><br>
   <div id='result1'></div>

   <!-- Script -->
   <script type="text/javascript">

   // Single search
   function hasClass(el,classname){

      if(el.classList.contains(classname)){
          document.getElementById('result1').innerHTML = 'True';
      }else{
          document.getElementById('result1').innerHTML = 'False';
      }
   }

   </script>
</body>
</html>

View Demo


2. Check multiple elements has class using JavaScript

In the previous section, we learned how to check if a specific class exists on a single HTML element. Now, we will take a step further and learn how to search for a particular class on multiple elements.

In this section, we will build upon the previously discussed hasClass() function and introduce a new function called checkClass(classname). This function is use to find all elements that has a specified class and display their IDs.

Example:

HTML

  • Created 3 <div> elements with the class "content". Two of the <div> elements have the additional class "red", and one has the class "blue".
  • A button with the label “Has class – red” is provided to initiate the search for elements with the class "red" on click.
  • The result of the class search will be displayed in a <div id="result2">.

JavaScript

Create 2 functions –

  • hasClass() –

This function is defined to check if an element contains a specific class. It takes two parameters: the element instance and the search class name. This function uses the classList.contains() method to determine if the specified class is present on the element and returns true or false accordingly.

  • checkClass() –

The checkClass(classname) function is designed to display the IDs of the <div> elements that have a specific class. It takes one parameter, classname, representing the class to be searched.

Upon clicking the button, the checkClass() function is called. It retrieves all elements with the class "content" using document.getElementsByClassName('content').

Iterates through the retrieved elements and uses the hasClass() function to check if each element has the desired class (“red” in this case).

If an element contains the class, its ID attribute is extracted using getAttribute('id'), and the ID is appended to the ids variable.

Finally, the ids containing the IDs of elements with the class "red" is displayed in the <div id="result2">.

Using this function display <div > ids that has red class.

<!DOCTYPE html>
<html>
<head>
     <meta charset="utf-8">
     <meta name="viewport" content="width=device-width, initial-scale=1">
     <title>How to Check if element has class in JavaScript</title>
</head>
<body>
     <style>
     .content{
          width: 100px;
          height: 100px;
          display: inline-block;
          color: white;
     }

     .red{
          background: red;
     }

     .blue{
          background: blue;
     }
     </style>

     <h2>Search class on multiple elements</h2>

     <div class='content red' id='div1'>div1</div>
     <div class='content blue' id='div2'>div2</div>
     <div class='content red' id='div3'>div3</div><br><br>
     <input type='button' value="Has class - red" id='check' onclick="checkClass('red');">

     <br><br>
     <b>Result</b><br><br>
     <div id='result2'></div>

     <script type="text/javascript">

     // Search class
     function hasClass(el,classname){

          if(el.classList.contains(classname)){
               return true;
          }else{
               return false;
          }
     }

     // Multiple search
     function checkClass(classname){
          var div = document.getElementsByClassName('content');
          var totalel = div.length;
      
          var ids = "";
          for(var i=0;i<totalel;i++){

               if(hasClass(div[i],classname)){
                    var divid = div[i].getAttribute('id');
                    ids += divid + ", ";
               }
               document.getElementById('result2').innerHTML = ids;

          }
     }
     </script>
</body>
</html>

View Demo


3. Conclusion

We learned how to use JavaScript to search for classes on single and multiple elements efficiently, using the classList property.

You can also view this tutorial to know class searching using jQuery.

If you found this tutorial helpful then don't forget to share.

Leave a Comment