How to check if an element has a certain class name with jQuery?

SAP HANASAPSAP Basis

To check if an element has a certain class name with jQuery, use the hasClass() method. You can try to run the following code to check if an element has a certain class name i.e. 'myclass' in the following example:

Example

Live Demo

<!DOCTYPE html>
<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
      <script>
         $(document).ready(function(){
             $("button").click(function(){
                 alert($("h2").hasClass("myclass"));
             });
         });
      </script>
      <style>
         .myclass {
           color: blue;
         }
      </style>
   </head>
   <body>
      <h2 class="myclass">Heading</h1>
      <p>This is demo text.</p>
      <button>Check: The h2 element has 'myclass' class?</button>
   </body>
</html>
raja
Published on 14-Dec-2017 16:51:44
Advertisements