Replace class in jquery

Many time developer face situation where they have to switch the class with other class and some another event they have to return back.

This code is the best way to replace a class. When you click first time on button then it remove the "even" class and add the "odd" class. But if you again click on button it do the reverse task this time it remove the "odd" class and add the "even" class.

In new version jQuery also introduce switchClass() method, but this method() not revert the changes.

CODE
<!DOCTYPE html>
<html>
<head>
  <title>Replace class in jquery</title>
  <script src="http://code.jquery.com/jquery-1.9.1.js" type="text/javascript"></script>
  <script type="text/javascript">
    $(function () {
      $('#btnChange').click(function () {
        if($('#container').hasClass('even')) {
          $('#container').removeClass('even').addClass('odd');
        }
        else {
          $('#container').removeClass('odd').addClass('even');
        }
      });
    });
  </script>
  <style>
    #container{height:100px;padding:10px;width:200px;}
    .even{background-color:red;}
    .odd{background-color:green;}
  </style>
</head>
<body>
  <div id="container" class="even">
    <button id="btnChange">Change</button>
  </div>
</body>
</html>
DISPLAY

No comments :

Please Give Your Feedback