Why classes change the order?

$("body").on("click", ".close", function() {
  var class_test1 = 'class1 class2';
  var class_test2 = 'class1 class3';
  $('#id_test').removeClass(class_test1).addClass(class_test2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="id_test" class="class1 class2">
  test
</div>
<button class="close">
  test
</button>

If click on button, div#id_test should be change classes on class1 class3, but he change classes on class3 class1(classes change the order). Why is this happening and have resolved problem?

P.S.: need change class1 class3 on class1 class2 - only in this order.

Answers 1

  • You can use .toggleClass() to toggle 2 , 3 at end of one of the className string

    $("body").on("click", ".close", function() {
      var n = 3;
      $("#id_test").toggleClass(function() {
        return "class2 class" + n;
      })
    });
    #id_test.class2 {
      color: green;
    }
    #id_test.class3 {
      color: blue;
    }
    #id_test.class2:after {
      content: attr(class);
    }
    #id_test.class3:after {
      content: attr(class);
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
    </script>
    <div id="id_test" class="class1 class2">
      test
    </div>
    <button class="close">
      test
    </button>


Related Articles