Home > database >  How can I add/remove class using $this
How can I add/remove class using $this

Time:12-17

Please see code below

$(".nwe-cl-icontext").click(function () {
  $(this).parent().toggleClass("nwe-active");
 //  $(this).removeClass("nwe-active");
})
.nwe-cl-c.nwe-active {
background: red;
}

.nwe-cl-c {
background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
    <div >
        <div ></div>
        <div >btn3</div>
    </div>

    <div >
        <div ></div>
        <div >btn2</div>
    </div>

    <div >
        <div ></div>
        <div >btn3</div>
    </div>
</div>

Can anyone help me with how can I accomplish this? Currently, by using toggleClass I can add/remove classes. But my goal is when I click the second button the nwe-class should add to the second parent same with the 3rd and so on the parent.

CodePudding user response:

So select the element with the class, make sure it is not the one you clicked on, and remove the class.

$(".nwe-cl-icontext").click(function() {
  const elem = $(this).parent();
  elem.toggleClass("nwe-active");
  $('.nwe-active').not(elem).removeClass("nwe-active");
})
.nwe-cl-c.nwe-active {
  background: red;
}

.nwe-cl-c {
  background: green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >
    <div ></div>
    <div >btn3</div>
  </div>

  <div >
    <div ></div>
    <div >btn2</div>
  </div>

  <div >
    <div ></div>
    <div >btn3</div>
  </div>
</div>

  • Related