Overview
From time to time in jQuery I want to check a condition of some kind, and then based on the result add/remove a cssClass to an element.
Before calling add(remove)Class, I always check to see if that class isn't (or is) applied already.
In code, this translates to
var myElement = $('#something'),
someClass = 'coolClass';
if (someCondition) {
// addClass, but only if that class isn't already on this element
if (!myElement.hasClass(someClass)) { myElement.addClass(someClass); }
} else {
// otherwise, removeClass, but only if it's already on this element
if (myElement.hasClass(someClass)) { myElement.removeClass(someClass); }
}
Is there a neater way of writing the above?
I'm sure there must be a nicer way of doing this, as the nested if statements smell to me.
Clarity on toggling
Just a clarifying note (added after the answers below). It is important to note here than toggleClass(className)
will not suffice as I explicitally want to remove or add based on a condition check - and need to account for the 'toggle' going out of sync. (Adam gives an example in a comment on Rob's answer below).