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>
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.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 useaddClass()andremoveClass():