How to add or remove class dynamically in jQuery

No comments
jQuery contains two classes addClass() and removeClass(). By using these classes we can add or remove classes dynamically. addClass() function used to add class and removeClass() function used to remove previously added classes.

For example if i have div tag (id=hiid) and i want to add 'activeclass' class then i will add addClass function as below:

$(#hiid’).addClass(‘activeclass’);

And if i need to remove above added class then i will write script as below:

$(#hiid’).removeClass(‘activeclass’);

Here is the complete example:

<html>
  <head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<style>
.activeclass{background:#000;color:#fff;}
</style>
 </head>
 <body>
  <div>
   <div id="hiid">This is div tag.</div>
<input type="button" name="addclass" id="addclass" value="Add Class" />
<input type="button" name="removeclass" id="removeclass" value="Remove Class" />
  </div>  
<script type="text/javascript">
$("#addclass").click(function () {
  
   $('#hiid').addClass('activeclass');
   
});
$("#removeclass").click(function () {
  
   $('#hiid').removeClass('activeclass');
   
    });
</script>
 </body>
 </html>

No comments :

Post a Comment