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

1 comment :

  1. 1xbet - No 1xbet Casino | Live dealer casino online
    1xbet is a reliable casino site Get air jordan 15 retro that offers a 스포츠 토토 great casino games Air Jordan 21 retro from 1xbet 먹튀 the best software providers for the regulated gambling markets. Rating: 8/10 · great air jordan 5 retro ‎Review by a Tripadvisor user · ‎Free · ‎Sports

    ReplyDelete