santa
santa

Reputation: 12512

Swap class w/jQuery

How can I make a conditional swap with jQuery on click. If certain class is present swap it to another, for example 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?

Upvotes: 0

Views: 813

Answers (2)

Matt Ball
Matt Ball

Reputation: 359786

.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
    });
});

Upvotes: 2

David
David

Reputation: 2331

$(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");

Upvotes: -1

Related Questions