Reputation: 129
I have the following CSS:
.red {background-color: #CC0000;}
.green {background-color: #009900;}
and my HTML is:
div class="red" id="ch1">Content</div>
<div class="red" id="ch2">Content</div>
<div class="red" id="ch3">Content</div>
...
<div class="green" id="ch..">Content</div>
<div class="red" id="ch..">Content</div>
and I am using the following script to change class on divs:
$(document).ready(function() {
$(".red , .green").click(function(){
$(".green").removeClass("green").addClass("red");
$(this).toggleClass('red green');
});
});
Works fine to change div class onclick from .red to .green but when I click on the "green" the div doesn't becomes "red". I other words I would like to have or all "red" or just ONE "green" div ALSO nothing is working if I change the sequence of .red - .green in my CSS
Any thoughts? Thanks in advance
Upvotes: 0
Views: 1567
Reputation: 325
Only using toggleClass() should work. So remove following line from your code $(".green").removeClass("green").addClass("red");
Solution:-
$(document).ready(function() {
$(".red , .green").click(function(){
$(this).toggleClass('red green');
});
});
Is this what you are expecting? http://jsfiddle.net/k23g3ne4/
Upvotes: 1
Reputation: 326
this is working :
$(this).siblings('.red , .green')
.removeClass("green")
.addClass("red");
Upvotes: 0
Reputation: 207501
Do not include the element that is clicked...
$(".green").not(this).removeClass("green").addClass("red");
Upvotes: 1