views:

614

answers:

1

Hi. I have 4 anchors, I want to add a class of current to an anchor as it is clicked and remove the class from the other 3 at the same time here's my code what am I doing doing wrong please?

if ($("ul#thumb a").hasClass("current") {
    $("ul#thumb a").removeClass("current");
    $(this).addClass("current");
});

and my html looks like this:

<ul id="thumbs">
    <li>
        <!-- intro page navi button -->
        <a id="t0" class="active" name="t0">The Company</a>

        <ul class="navi">
            <li><a style="display:none"></a></li>
            <li><a id="t1" name="t1">The Brief</a></li>
            <li><a id="t2" name="t2">The Solution</a></li>
            <li><a id="t3" name="t3">The Result</a></li>
        </ul>

    </li>
</ul>

Thanks.

+6  A: 

Update:

Since you've updated your question with your HTML, I've worked up a different solution:

$(function(){
  $("#thumbs > li > a").click(function(e){
    e.preventDefault();
    $("#thumbs > li > a").addClass("active").not(this).removeClass("active");
  });
});

Demo Online: http://jsbin.com/oxezo/edit


You're missing the last ) on your if statement. You're also not specifying which a you would like to test hasClass() against. If you just want to know if any have it, you can check the length property following your jQuery selector.

If they are siblings, you can do this with chaining:

$("ul#thumb a").click(function(e){
  e.preventDefault();
  $(this).addClass("current").siblings().removeClass("current");
});
Jonathan Sampson
+1 - Good catch. I edited the post and didn't see that =P
Topher Fangio
@Jonathan I have amended my post to show my html
mtwallet
@Jonathan Sampson what does `e.preventDefault();` mean? +1 by the way
c0mrade
@c0mrade: It prevents the default action of the link.
Jonathan Sampson