See code below:
$(".btn").on("click", function(){
$(".main-div").toggleClass("active");
});
.main-div.active {
background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="one">
<div class="btn">ClickMe1</div>
<div class="main-div">Div1</div>
</div>
<div class="one">
<div class="btn">ClickMe2</div>
<div class="main-div">Div2</div>
</div>
Hi guys, can you help me with this matter? Well my goal is to when I click the first button it should only add class on the first
.main-div
however, by using toggle it adds also on the second div. Can anyone help me how to implement it correctly?
1 Answer 1
$(".btn").on("click", function(){
$(this).next(".main-div").toggleClass("active");
});
.main-div.active {
background: yellow;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="one">
<div class="btn">ClickMe1</div>
<div class="main-div">Div1</div>
</div>
<div class="one">
<div class="btn">ClickMe2</div>
<div class="main-div">Div2</div>
</div>
Your problem is the $(".main-div").toggleClass("active");
selects every .main-div
, not just the sibling element.
The easiest way to select the next sibling with the .main-div
class is $(this).next(".main-div").toggleClass("active");
You can read more about jQuery selectors at https://api.jquery.com/category/selectors/
3 Comments
.next
is only working if you have 2 div's on your .main-div
. What if you have many? Thanks.main-div
as you want, assuming you keep that same structure with a single .main-div
per parent .one
div. If you want to use multiple .main-div
in the same parent then you can use $(this).parent().children(".main-div").toggleClass("active");
, however it will highlight all the .main-div
in that parent