maftyycs maftyycs - 3 months ago 8
Javascript Question

Give a class of "selected" when clicked on another <a> then remove the class if it's the same <a>

I am trying to change

$('h2 a').on('click', function(){
$('h2 a.selected').removeClass('selected');
$(this).addClass('selected');
});


I made an Accordion, the first tab has class
selected
. So when I click on another tab, it removes
selected
from the first tab and gives the one I clicked on
selected
, if I click on the same tab I just opened, it removes
selected
.

Answer

You can use .is(), .filter()

var h2 = $("h2 a");

h2.on("click", function() {
  if ($(this).is(".selected")) {
    $(this).removeClass("selected");
  } else {
    h2.removeClass("selected")
      .filter(this).addClass("selected")
  }
});
.selected {
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<h2>
<a>a</a>
<a>b</a>
<a>c</a>
</h2>

Comments