santa
santa

Reputation: 12512

toggleClass with jquery

I need to swap the class in a span placed withing a link based on a condition whether the link has a particular class in it or not. Tried this but it doesn't seem to work. What am I missing?

if ($("#myLink").hasClass("dis")) {
    $("#myLink").find("span").toggleClass("uico", "uicoGR");
} else {
    $("#myLink").find("span").toggleClass("uicoGR", "uico");
}

<a href="#" id="myLink" class="dis"><span class="uico"></span></a>

Upvotes: 0

Views: 448

Answers (3)

jfriend00
jfriend00

Reputation: 708066

If you insist on using the dual class method, then Gus has the right answer here, but I would challenge whether you need this code at all. If these classes are being used for CSS, then you don't need any of this javascript because you already have enough information to discern the two states in CSS selectors without adding/removing uicoGR or uico.

The first state (what you were using .uicoGR for) is this CSS selector:

#mylink span {put your CSS here}

The second state (what you were using .uico for) is this CSS selector:

#mylink.dis span {put your CSS here}

The second state will override the CSS for the first state when the class "dis" is present.

Upvotes: 1

Gus
Gus

Reputation: 7349

The two classnames to be toggled should be passed in the first parameter, separated by spaces.

Also, the hasClass() condition can be added to the selector.

$('.dis#mylink span').toggleClass('uico uicoGR') ;

Edit

Reading the question again, it's not clear that you appreciate what toggleClass() does. This function looks for all classes named and either adds them if they are not found, or removes them if they aren't. It would appear that what you are after is adding or removing classes based on whether a third class is found. For this, just use addClass() and removeClass():

$('#mylink').each(function() {
  if($(this).hasClass('dis')) {
    $(this).find('span').addClass('uicoGR').removeClass('uico') ;
  } else {
    $(this).find('span').addClass('uico').removeClass('uicoGR') ;
  }
}) ;

Upvotes: 3

Michał Wojciechowski
Michał Wojciechowski

Reputation: 2490

The classes should be passed in a single string parameter, separated by spaces, e.g.:

$("#myLink").find("span").toggleClass("uico uicoGR");

Upvotes: 3

Related Questions