Toggle CSS class - Javascript DOM

Javascript examples for DOM:Element classList

Description

Toggle CSS class

Demo Code

ResultView the demo in separate window

<html>
   <head> 
      <style type="text/css">

.class1 {//from  w w  w.ja  v  a  2s  . com
   color: #f00;
}
.class2 {
   color: #00f;
}

      </style> 
   </head> 
   <body> 
      <div id="div" class="class1">
         click here
      </div> 
      <script>
function classToggle() {
    this.classList.toggle('class1');
    this.classList.toggle('class2');
}
document.querySelector('#div').addEventListener('click', classToggle);

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

Related Tutorials