Reputation: 4611
<ul>
<li><a class="selected">A</a></li>
<li><a>B</a></li>
<li><a>C</a></li>
</ul>
How can I remove the attribute selected from all <li>'s
when one of the element is clicked and set the one being clicked to selected?
I'm learning jquery.
Updated the code
Upvotes: 1
Views: 661
Reputation: 382716
You can modify the code like this for the links:
$(function(){
$('#container ul > li > a').click(function(){
$(this).siblings('.selected').removeClass('selected');
$(this).addClass('selected');
});
});
You can do this way:
$(function(){
$('#container ul > li').click(function(){
$(this).siblings('.selected').removeClass('selected');
$(this).addClass('selected');
});
});
The siblings()
method is used to find the surrounding siblings of the clicked element and then removeClass
is used to remove the selected class that has one. Later addClass
is used to apply the selected class to clicked element referred to with $(this)
. The container
in code above is supposed to be the id of element which contains your list.
Note also that click event fits for links or buttons rather than lists :)
Upvotes: 3