tags:

views:

34

answers:

2

hi,

i'm adding a class to an <a> tag on "click". now i need to remove this class when another <a> is clicked. how can i do this?

thanks

EDIT: the html is an unordered list

<ul>
 <li><a href="">link1</a></li>
 <li><a href="">link2</a></li>
 <li><a href="">link3</a></li>
 <li><a href="">link4</a></li>
</ul>
+1  A: 

without knowing the html, this is rough.

$('a').click(function(){
   $('a').removeClass('red')
   $(this).addClass('red');
   return false;
})

crazy demo

based on your EDIT, the best approach I could suggest is

$('li a').click(function() {

    $(this).addClass('red')
        .parent()
        .siblings()
        .children('a')
        .removeClass('red');

    return false;
})​;

humble demo

if your classes are just meant for CSS purpose, I would suggest to add/remove class on li, to minimize codes on javascript part.

$('li a').click(function() {

    $(this).parent()
        .addClass('red')
        .siblings()
        .removeClass('red');

    return false;
})​;

then have your CSS

Before

a.red {
   color: red;
}

after

li.red a {
    color: red;
}

cool demo

Reigel
perfect. thanx!
pixeltocode
you're welcome ^_^
Reigel
+2  A: 

here's one

var lastSelected;

$('ul').delegate('a', 'click', function (e) {

    if(lastSelected) {
        lastSelected.removeClass('selected');
    }

    lastSelected = $(this).addClass('selected');

});
Shrikant Sharat
+1 for using delegate and encouraging it's use here, where it is well suited.
mkoistinen
yeah, `delegate`'s my favorite *function* in jQuery's event-related stuff (favorite *functionality* would be event namespaces :D)
Shrikant Sharat