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.