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
source share
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

, a.xx. a.yy click. , , :

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

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

, . : , . , .

0
source

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

Try the following:

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

Source: https://habr.com/ru/post/1766217/


All Articles