Search code examples
javascriptjqueryaddclassremoveclass

How do I add then remove class on outer div on each clink


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>

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