jQuery "active" class assignment

user120944 picture user120944 · Aug 11, 2009 · Viewed 26.6k times · Source

All I am trying to accomplish is to be able to have an unordered list of links in which one is clicked, the parent list item is assigned the class "active." Once another link is clicked within that list, it checked to see if "active" is assigned, remove it from that list item, and add it to the most recent clicked links parent list item.

Example:

Step One - User has clicked the link "I am link two"

<ul>
<li><a href="#">I am link one</a></li>
<li class="active"><a href="#">I am link two</a></li>
</ul>

Step Two - User has now clicked the link "I am link one"

<ul>
<li class="active"><a href="#">I am link one</a></li>
<li><a href="#">I am link two</a></li>
</ul>

Pretty simple, but man I beat me up.

Answer

Lior Cohen picture Lior Cohen · Aug 11, 2009

Assumption: the UL element has the class 'linksList'.

$('.linksList li a').click(function()
{
  $('.linksList li').removeClass('active');
  $(this).parent().addClass('active');
});