1
<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

3 Answers 3

3

Update:

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 :)

Sign up to request clarification or add additional context in comments.

1 Comment

I forgot that the attribute selected is actually inside an <a> tag. I updated my question.
0

Use addClass and removeClass.

Comments

0

removeAttr('class') or removeClass('selected')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.