Sunday, May 12, 2024
 Popular · Latest · Hot · Upcoming
87
rated 0 times [  92] [ 5]  / answers: 1 / hits: 25412  / 12 Years ago, thu, march 1, 2012, 12:00:00

How to add a class to an element only if it already does not have it? Say we don't know if the element has class=desired_class ... but we want to make sure it has.


More From » jquery

 Answers
112

try this



var elem = $('selector');
if(!elem.hasClass('desired_class')){
elem.addClass('desired_class');
}

[#87113] Wednesday, February 29, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jesse

Total Points: 513
Total Questions: 118
Total Answers: 106

Location: Denmark
Member since Tue, Jul 19, 2022
2 Years ago
;