0

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>
0

1 Answer 1

2

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");
  });
});
Sign up to request clarification or add additional context in comments.

4 Comments

always try to provide expected behavior also along with some basic html structure... I had to assume there were other elements involved ...and happened to guess correctly
Oh yeah, I just realised that it does not work correctly, because it adds the hero-selected to another div too, and it shouldnt. It still works but I think it does more than it should. Let me add the html in a sec.
With the code it also gets added to the div with the class hero-mini
fixed...just needed the ".hero-build" selector in children()

Your Answer

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.