Home > OS >  How to remove/add class on main parent
How to remove/add class on main parent

Time:11-29

Hi please see code below:

My goal is if I click the 1st button it will add class on main parent and if I click it again it will remove class. But if I click the other button the class on 1st main parent will remove and it will add to 2nd main parent. Can anyone help me how to accomplish that?

$(".main-btn").on("click", function() {
  $(this).closest(".main").addClass("addClass");
});
.main {
  background: yellow;
  margin-bottom: 3px;
  height: 50px;
  
}

.main.addClass {
  background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
        <div >Button</div>
  <div >
  </div>
    <div >
  </div>
    <div >
  </div>
</div>

<div >
  <div >Button</div>
</div>

<div >
  <div >Button</div>
</div>

CodePudding user response:

We can do it via below functions:

  1. siblings() to get siblings elements and remove the addClass

  2. toggle() to switch the class of current clicked element

$(".main-btn").on("click", function() {
  $(this).closest(".main").siblings().removeClass("addClass");
  $(this).closest(".main").toggleClass("addClass");
});
.main {
  background: yellow;
  margin-bottom: 3px;
  height: 50px;
  
}

.addClass {
  background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
        <div >Button</div>
  <div >
  </div>
    <div >
  </div>
    <div >
  </div>
</div>

<div >
  <div >Button</div>
</div>

<div >
  <div >Button</div>
</div>

  • Related