Neater Way Of Checking Adding/removing A CSS Class Using 'hasClass' In JQuery?
Solution 1:
var myElement = $('#something'),
someClass = 'coolClass';
myElement.toggleClass(someClass, someCondition);
toggleClass
does your check for you essentially. If you do a toggleClass('class', true)
it'll only actually put that class on there if it's not already, and will never add more than one class of the same name.
Solution 2:
Use the toggleClass
method, which removes a class if it exists, and adds it if it does not.
var myElement = $('#something'),
someClass = 'coolClass';
myElement.toggleClass(someClass, someCondition);
Reviewing your current code, I add that there's no need to use hasClass
. jQuery automatically deals correctly with the request: A class name is only added once, so using $("<a>").addClass("xxx").addClass("xxx").attr("class")
will return x
, instead of xxx xxx
.
Solution 3:
.addClass() will only add a class if it doesn't already exist and .removeClass() only removes an existing class so the following should work:
if (someCondition) {
myElement.addClass(someClass);
} else {
myElement.removeClass(someClass);
}
Solution 4:
Since jQuery 1.4 there is a neater way of doing this using toggleClass
function. See details here.
Solution 5:
this should do it as well
if (someCondition) {
$(myElement+":not(.someClass)").addClass(someClass);
}else{
$(myElement+":has(.someClass)").removeClass(someClass);
}
Post a Comment for "Neater Way Of Checking Adding/removing A CSS Class Using 'hasClass' In JQuery?"