Others



Add Class and Remove Class in JavaScript


We can get all class names of an element using classList Property. We can add a class name to classList using add() method. And remove a class name from classList using remove() method.

Add, Remove Class
var cls=document.querySelector(".menu");
if(cls.classList.contains('hide')){
  cls.classList.remove('hide');
}else{
  cls.classList.add('hide');
}
Try it Yourself

The following example shows, how to create the hide and show menu using JavaScript with add class and remove class.

Example
<html>
  <head>
    <style>
      .menu{
        padding:10px;
        width:100px;
        border:1px solid #ccc;
        margin-top:10px;
      }
      .menu a{
        display:block;
        margin-bottom:10px;
      }
      .hide{
        display:none;
      }
    </style>
  </head>
  <body>
    <input type='button' value='Show' onclick='menuItem(this)'>
    <div class='menu hide'>
      <a href='#'>Home</a>
      <a href='#'>Product</a>
      <a href='#'>About Us</a>
      <a href='#'>Contact Us</a>
    </div>
    <script>
      function menuItem(ele){
        var cls=document.querySelector(".menu");
        if(cls.classList.contains('hide')){
          cls.classList.remove('hide');
          ele.value='Hide';
        }else{
          cls.classList.add('hide');
          ele.value='Show';
        }
      }
    </script>
  </body>
</html>
Try it Yourself

Demo