Rana
Rana

Reputation: 4611

use jquery to modify class attribute

<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

Answers (3)

Sarfraz
Sarfraz

Reputation: 382716

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

Upvotes: 3

user382538
user382538

Reputation:

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

Upvotes: 0

Abe Miessler
Abe Miessler

Reputation: 85056

Use addClass and removeClass.

Upvotes: 0

Related Questions