Alex Rivera | Logout

toggleClass and remove class from all other elements

Asked 2011-02-20T13:04:54.253
23

How can I toggleClass and remove class from all other elements? Consider a div that contains a tags: html:

<div class="size">
   <a href="">blahblah</a>
   <a href="">blahblah</a>
</div>

jQuery:

 $(".size a").click(function(){
 $(this).toggleClass('checked');
 if($(".size a").hasClass('checked')){
     $(this).removeClass('checked');
  }
 })

I want to add class "cheched" to element and remove the class "ckeched" from other elements that have class "checked" . My code remove all classes. How can I add specific class and remove other element's class with click? Thanks in advance

Edit
Report

1 Answer

1

I'm assuming that you have a class 'size' that contains a number of elements of which only one should be able to have the class 'checked' at any one time.

$(".size a").click(function()
{
    if($this).hasClass('checked')
    {
        $(".size a").removeClass('checked');
        $(this).addClass('checked');
    }
    else
    {
        $(this).removeClass('checked');
    }
}
answered 2011-02-20T13:14:02.483

Your Answer