开发者

Swap class w/jQuery

开发者 https://www.devze.com 2023-03-14 11:09 出处:网络
How can I make a conditional swap with jQuery on click. If certain class is present swap it to another, for exam开发者_StackOverflowple swap class \"A\" to \"B\".

How can I make a conditional swap with jQuery on click. If certain class is present swap it to another, for exam开发者_StackOverflowple swap class "A" to "B".

<a href="#" id="clickMe"><span class="A"></span>link</a>

I've been trying this but it does not seem to work:

$(this).closest("span").toggleClass("A,B");

What am I missing?


.closest() goes up the DOM tree, not down.

Use .children() or .find().

$(function ()
{
    $('#clickMe').click(function ()
    {
        $(this).children('span').toggleClass('a b');
        return false; // don't follow the link
    });
});

.toggleClass() expects multiple class names to be separated by spaces, not commas.

If you only want the class swap to happen once:

$(function ()
{
    $('#clickMe').click(function ()
    {
        var $span = $(this).children('span:first');
        $span.toggleClass('a b', $span.hasClass('a'));
        return false; // don't follow the link
    });
});


$(this).closest("span").removeClass("A").addClass("B");

Edit: the above will forcibly replace class A with class B. I think what you're looking for is to toggle between A and B every time the code runs, correct? Try:

$(this).closest("span").toggleClass("A B");
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号