Wondering
Wondering

Reputation: 5096

how to change class of <a> tags in jquery

I have a table structure, something similar to

<table style="width: 100%;">
    <tr>
        <td>
            <a href="#" class="xx">one</a>
        </td>
        <td>
    </tr>
    <tr>
        <td>
            <a href="#" class="xx">Two</a>
        </td>
        <td>
    </tr>
    <tr>
        <td>
            <a href="#" class="xx">Three</a>
        </td>
        <td>
    </tr>
</table>

css:

.xx {
    border: 5px solid green;    
}

.yy {
    border: 5px solid red;    
}

Now what I expect is, if I click on 1st row/1st <a> its border will turn to red, and rest of <a> in green, again if I clcik on 1st row/1st <a> it should turn to green. Also if I click on any other <a> then only it should turn to red, but rest of the <a> should be green.

I tried:

$(function () {
    $("a.xx").click(function () {
        if ($(this).hasClass("xx")) {
            $(this).removeClass("xx").addClass("yy");
        } else {
            $(this).removeClass("yy").addClass("xx");
        }
    });
});

But it's not working.

Upvotes: 1

Views: 187

Answers (4)

Nick Craver
Nick Craver

Reputation: 630587

You need to tweak the handler a bit, you can do so using .toggleClass() to swap classes, like this:

$("a.xx").click(function() {
  $(".yy").not(this).toggleClass("xx yy");
  $(this).toggleClass("xx yy");
});

You can give it a try here, .toggleClass() takes multiple classes separated by a space, so to swap 2 classes just pass both. In this case you want to on any that was toggle .yy and the current clicked element.

Or, since .yy is defined last in the CSS (and overrides the same properties) you can just add that class, like this:

$("a.xx").click(function() {
  $(".yy").not(this).removeClass("yy");
  $(this).toggleClass("yy");
});​

You can give it a try here.

Upvotes: 3

Sjoerd
Sjoerd

Reputation: 75659

You only change the class of $(this), so none of the other links will change color.

Try this:

        $("a.xx").click(function () {
            $('a.yy').removeClass('yy').addClass('xx');
            $(this).removeClass('xx').addClass('yy');
        });

Upvotes: -1

Amadan
Amadan

Reputation: 198476

Your code says nothing about turning other things green. You need to do two things upon a click: turn everything green, then turn the current one red. You are doing the second part, but not the first one.

Upvotes: 0

bryan.taylor
bryan.taylor

Reputation: 584

It's because you are attaching a handler only to the a.xx click event. You also need one for the a.yy click event. What I would recommend is adding another class for these highlights then going from there, like this:

<a href="#" class="xx highlight"></a>

$('a.highlight').click(function({
  $('a.xx,a.yy').toggleClass('xx yy');
});

Upvotes: 0

Related Questions