April 4, 2012

jquery how can i change only link class when this link ic clicked

Question by ahmedsaber111

i have a li items i need to change class of the clicked items as follow

  • remove class current from the default one
  • add class current to the clicked one

my html code here

                <ul class="filter">
                <li><a href="#" title="" class="current">recent</a></li>
                <li><a href="#" title="">top popularity</a></li>
                <li><a href="#" title="">top commented</a></li>
                <li><a href="#" title="">other ...</a></li>

            </ul>

and here is the jquery code to do that job

      $(".filter > li a").click(function(){

      $(".filter li a.current").removeClass("current");
        $(this).addClass("current");
      });

it works perfect otherwise when i clicked on any link else these links it apply that code to it, i need to apply this code only to ul.filter

Answer by nnnnnn

If you want the click processing to occur only within ul.filter then you should update your selector to reflect that:

$("ul.filter > li a")

Rather than

$(".filter > li a")

If you have more than one ul element with the “filter” class and you only want to apply the functionality to one of them then you should give that particular ul an id and change your selector to use the id.

Answer by Starx

Use :not() to omit the current item

   $(".filter > li a").not(".current").on('click', function(){
       if(!$(this).hasClass("current")) {
           $(".filter").find("a.current").removeClass("current");
           $(this).addClass("current");
           alert($(this).html());
       }
   });

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!