Search code examples
jqueryaddclassremoveclasstoggleclass

Jquery addClass removeClass if clicking same class


This code below works. I am trying to also add that if the .hero-build-wrap already added the class to hero-build , and you click it again it removes it. I tried with .toggleclass instead of .addClass but didnt work

$(function() {
  $(".hero-build-wrap").click(function() {
    $(".hero-build").removeClass("hero-selected");
    $(this).children(".hero-build").addClass("hero-selected");
  });
});

The HTML:

<div class="hero-build-wrap">
   <a class="hero-mini hero-mini-assa">
     <img class="hero-hover-big" src="">
     <img class="hero-hover-small"src=">
   </a>
   <div class="hero-build hero-selected">
      <a href="">
        <p>This is a test</p>
      </a>
      <a href="">
        <p>Anothertest</p>
      </a>
   </div>
</div>

Solution

  • Remove the line that adds the class

    $(function() {
      $(".hero-build-wrap").click(function() {    
        $(this).children(".hero-build").toggleClass("hero-selected");
      });
    });
    

    If you add a class , then toogle that class , the end result would be it would cancel adding it


    That being said, you may also be trying to remove the class elsewhere since $().children is a very strange call

    If so you can do something like:

    $(function() {
      $(".hero-build-wrap").click(function() { 
        var $children =  $(this).children(".hero-build").toggleClass("hero-selected");
        $('.hero-selected').not($children).removeClass("hero-selected");
      });
    });