TheNone TheNone - 1 year ago 137
jQuery Question

toggleClass and remove class from all other elements

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

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


$(".size a").click(function(){
if($(".size a").hasClass('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

Answer Source

This will do it

 $(".size a").click(function(){
    $('.size a.checked').not(this).removeClass('checked');


Alternatively you could do

 $(".size").on('click','a', function(){
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download