Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - adding class to li on click

Tags:

jquery

I have the following markup

<div id="div1">
   <ul>
      <li><a href="#" id="id1">link1</a></li>
      <li><a href="#" id="id2">link2</a></li>
      <li><a href="#" id="id3">link3</a></li>
   </ul>
</div>

I want to use jQuery to add a class to the clicked link and remove the class from previously clicked links, like

<li class="selected"><a href="#" id="id1">link1</a></li>
<li><a href="#" id="id2">link2</a></li>
<li><a href="#" id="id3">link3</a></li>
like image 358
ZedBee Avatar asked Dec 05 '22 12:12

ZedBee


1 Answers

Try this:

$('#div1 li').click(function(e) {
    $(this).addClass('selected').siblings().removeClass('selected');
});

Alternatively, if you want to attach the click event to the a:

$('#div1 a').click(function(e) {
    e.preventDefault();
    $('#div1 a').removeClass('selected');
    $(this).addClass('selected');
});

Example fiddle

like image 84
Rory McCrossan Avatar answered Dec 23 '22 21:12

Rory McCrossan