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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With