Implement jQuery's addClass function with Javascript function - Javascript DOM

Javascript examples for DOM:Element className

Description

Implement jQuery's addClass function with Javascript function

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <meta name="viewport" content="width=device-width, initial-scale=1"> 
      <style id="compiled-css" type="text/css">

.red {color:red;}


      </style> 
      <script type="text/javascript">
    window.onload=function(){/*from   w w  w .j  a  v a 2  s .  c o  m*/
Element.prototype.addClass = function(cl) {
    this.className += (this.className ? ' ' : '') + cl;
}
document.getElementById("test").addClass("red");
    }

      </script> 
   </head> 
   <body> 
      <span id="test">hello</span>  
   </body>
</html>

Related Tutorials