0

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

3 Answers 3

1

Do not include the element that is clicked...

$(".green").not(this).removeClass("green").addClass("red");
Sign up to request clarification or add additional context in comments.

Comments

1

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/

Comments

0

this is working :

$(this).siblings('.red , .green')
  .removeClass("green")
  .addClass("red");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.