1

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?

asked Oct 25, 2021 at 3:22

1 Answer 1

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/

answered Oct 25, 2021 at 3:38

3 Comments

thanks for this idea I'll look into it now :)
hi thanks for this idea however using .next is only working if you have 2 div's on your .main-div. What if you have many? Thanks
It should work for as many blocks with.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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.