Reputation: 1294
I think this question might already been asked, but I can't find any answer working nor questions that reflect my problem. My problem is I currently have 2 <div>
's and I would like them to switch class after a onClick
event.
For example, when I click on a div, I'd like it to have a class called isSelected
and if the 2nd div have the class, I'd like to remove it. I don't simply want the clicked div to toggle isSelected
, I'd want the other div to 'loose' it's isSelected
class.
Upvotes: 0
Views: 571
Reputation: 4953
This should do what you need.
$("div").click(function(){
$("div").removeClass("isSelected");
$(this).addClass("isSelected");
});
.isSelected {
background-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="">1</div>
<div class="">2</div>
<div class="">3</div>
Upvotes: 0
Reputation: 95
Assuming one div will allways have the class you can use
$("#myDiv").on("click", function() {
$('#div1, #div2').toggleClass('isSelected');
})
Upvotes: 0
Reputation: 6538
$("div").click(function(){
$("div").removeClass("isSelected");
$(this).addClass("isSelected");
});
.isSelected {
background-color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="">test 1</div>
<div class="">test 2</div>
<div class="">test 3</div>
Upvotes: 1
Reputation: 16831
You could simply use a class selector to target any element with the certain class, and remove it....
$("#myDiv").on("click", function() {
$(".isSelected").removeClass("isSelected");
$(this).addClass("isSelected");
});
This would work no matter how many selectable divs you have...
Upvotes: 1
Reputation: 68393
try
$(".divclass").click(function(){
$(".divclass").removeClass("isSelected");
$(this).addClass("isSelected");
});
Assuming these two siblings have same class divclass
Upvotes: 1