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

JavascriptWeb DevelopmentFront End Technology

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

Live Demo

<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>
raja
Published on 08-Feb-2018 06:58:20
Advertisements