Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Simplest method for adding/removing a class between li elements

Tags:

html

jquery

I have a list of links, and I would like to use jQuery to set the clicked one as active, and have the rest of them remove their class.

My current setup is like this:

html

<ul>
  <li id="li_1" class="active"><a href="#" id="link1">link 1</a></li>
  <li id="li_2"><a href="#" id="link2">link 2</a></li>
  <li id="li_3"><a href="#" id="link3">link 3</a></li>
</ul>

jquery

$("#link1").click(function () {
  $("#li_1").removeClass('active');
  $("#li_2").removeClass('active');
  $("#li_3").addClass('active');
});
$("#link2").click(function () {
  $("#li_1").addClass('active');
  $("#li_2").removeClass('active');
  $("#li_3").removeClass('active');
});
$("#link3").click(function () {
  $("#li_1").removeClass('active');
  $("#li_2").addClass('active');
  $("#li_3").removeClass('active');
});

Obviously this isn't pretty in the least, and I'd like to have it become an extremely simple and flexible 1-2 liner function. I know this is possible, but unfortunately I don't possess the jQuery-fu that I know many of you do :)

like image 847
the_e Avatar asked Dec 13 '22 20:12

the_e


1 Answers

$('ul > li > a').click(function() {
    $(this).parent().addClass('active').siblings().removeClass('active');
    return false;
});

Or perhaps better would be to place an ID on the <ul> :

$('#myUL > li > a').click(function() {
    $(this).parent().addClass('active').siblings().removeClass('active');
    return false;
});
  • http://api.jquery.com/parent/
  • http://api.jquery.com/siblings/
like image 134
user113716 Avatar answered May 25 '23 20:05

user113716