Question

If id of li a item matches the class of div item a want to add a class "theme" on each click.

If id of li a item doesn't matches the class of div item a want to remove the class "theme" from non matching divs.

But it only adds the class on each click but doesn't remove class. Any suggestions?

<ul class="funding-theme">   
  <li data-rel="all"><a class="sub active" id="all" href="javascript:void(0)">All</a></li>
  <li><a class="sub" id="education" href="javascript:void(0)">Education</a></li>
  <li><a class="sub" id="healthcare" href="javascript:void(0)">Healthcare</a></li>
  <li><a class="sub" id="justice" href="javascript:void(0)">Justice</a></li>
</ul>

<div class="list left">
  <div class="non_profit all education"></div>
  <div class="non_profit all education"></div>
  <div class="non_profit all justice"></div>
  <div class="non_profit all healthcare"></div>
</div>

<script>

  var $sub  = $(".sub");

  $sub.click(function(e){

    if (e.target.id == "all") {
      //alert("#" + $(this).attr('id') + "");

      $("."+$(this).attr('id')).removeClass('theme');
    } else if (e.target.id == $(this).attr('id')) {
      alert("#" + $(this).attr('id') + "");

      $("."+$(this).attr('id')).removeClass('theme');
      $("."+$(this).attr('id')).addClass('theme');
    }
  });

</script>
Was it helpful?

Solution

Try this

$('.sub').click(function (e) {
var id = ($(this).attr("id"));    
    $('.list').find('div').each(function(){
        if($(this).hasClass(id))
        {            $(this).addClass('theme');
        }else
        {
            $(this).removeClass('theme');
        }
    });
});

Fiddle Demo

OTHER TIPS

Try this:

var $sub  = $(".sub");

$sub.click(function(e){

if (e.target.id == "all") {
  //alert("#" + $(this).attr('id') + "");

  $(".theme").removeClass('theme');
} else if (e.target.id == $(this).attr('id')) {
  alert("#" + $(this).attr('id') + "");

  $(".theme").removeClass('theme');
  $("."+$(this).attr('id')).addClass('theme');
}});

Working Demo

If I got this right, you need to change the following lines:

 $("."+$(this).attr('id')).removeClass('theme');
 $("."+$(this).attr('id')).addClass('theme');

to

$(".all").removeClass('theme');
$("."+$(this).attr('id')).addClass('theme');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top