on click, add class to alternative div with jQuery

I have two divs, div1 and div2. On clicking any of these div, I want to remove class .active from it and add that class to the other div.

I’m trying following code, but I cant figure out how to add the class to the other div which is not clicked. Thanks.

$('.div').click(function() {
  $(".div").removeClass("active");
});
.div1 {
  background: green;
  display: none;
}
.div2 {
  background: red;
  display: none;
}
.active {
  display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div div1 active">div1</div>
<div class="div div2">div2</div>

Fiddle http://jsfiddle.net/vLLtLwxy/


solution

Since there are only two elements, you could just use .toggleClass().

Updated Example

$('.div').click(function(){
  $(".div").toggleClass("active");
});

Similarly, it’s worth pointing out that you could also negate one of the elements using .not():

Example Here

$('.div').click(function(){
  $(this).removeClass("active");
  $('.div').not(this).addClass('active');
});