How to change <a> tag class 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 do I expect, if I press the 1st line / 1st <a>, its border will turn red and the rest <a>will be green, again, if I clcik on the 1st line / 1st <a>, it should turn to green . Also, if I click on any other <a>, then it should only be red, but the rest <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 does not work.
+1
4 answers
You need to configure the handler a bit, you can do this using .toggleClass()class replacement, for example:
$("a.xx").click(function() {
$(".yy").not(this).toggleClass("xx yy");
$(this).toggleClass("xx yy");
});
, .toggleClass() , , 2 . , .yy , .
, .yy CSS ( ), , :
$("a.xx").click(function() {
$(".yy").not(this).removeClass("yy");
$(this).toggleClass("yy");
});
+3