See code below:
$(".btn").on("click", function () {
$(".main-div").toggleClass("active");
})
.main-div.active {
background: red;
}
<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="test-div">test</div>
<div class="main-div">Div1</div>
</div>
<div class="one">
<div class="btn">ClickMe2</div>
<div class="test-div">test</div>
<div class="main-div">Div2</div>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Hi guys, just can anyone help me regarding this? My goal is when I click the 1st button the active class should add on the main div on its .main-div
. Also when I click the second button the active class on 1st div removes and adds on the second .main-div
and so on. Currently using toggle its add all the main-div
Can anyone help me with this? Thank you in advance.
CodePudding user response:
You can add / remove class and search using siblings instead.
$(".btn").on("click", function () {
//remove all existing active
$(".main-div").removeClass("active");
//add to sibling of btn
$(this).siblings(".main-div").addClass("active");
})
.main-div.active {
background: red;
}
<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="test-div">test</div>
<div class="main-div">Div1</div>
</div>
<div class="one">
<div class="btn">ClickMe2</div>
<div class="test-div">test</div>
<div class="main-div">Div2</div>
</div>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>