Computer >> Computer tutorials >  >> Programming >> Javascript

How to test if an element contains class in JavaScript in HTML


Use the hasClass() method to test if an element contains a JavaScript class.

Example

You can try to run the following code to test if an element i.e. <div> here contains a class

<html>
   <body>
      <div id="test" class="myClass"></div>
      <script>
         function hasClass(element, cls) {
            return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
         }
         var val1 = document.getElementById('test');
         alert(hasClass(val1, 'myClass'));
     </script>
   </body>
</html>