Add class to div when clicked to change its CSS style - Javascript DOM

Javascript examples for DOM:Element classList

Description

Add class to div when clicked to change its CSS style

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">

.selected {/*from   w  w w .  ja v  a 2 s .c  o m*/
   color: red;
}


      </style> 
   </head> 
   <body> 
      <div class="initialclass" onclick="choose(this)">
         CLICK
      </div> 
      <script type="text/javascript">
function choose(el) {
    el.classList.add("selected");
}

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

Related Tutorials