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.
You need to tweak the handler a bit, you can do so using
.toggleClass()to swap classes, like this: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.yyand the current clicked element.Or, since
.yyis defined last in the CSS (and overrides the same properties) you can just add that class, like this:You can give it a try here.