Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should hasClass precede removeClass - jQuery

Tags:

jquery

Is it necessary to check if a class exists before I use the removeClass api on an jquery object? eg.

if($(this).hasClass("test"))    $(this).removeClass("test"); 

or

$(this).removeClass("test"); 

if not necessary, why so?

like image 464
user917670 Avatar asked Jun 05 '12 10:06

user917670


1 Answers

Use just this:

$(this).removeClass("test"); 

There is no need to check for class existence.

From jQuery sources we can see that removeClass method uses replace method to remove the substring:

className = (" " + elem.className + " ").replace(rclass, " "); for (c = 0, cl = classNames.length; c < cl; c++) {     className = className.replace(" " + classNames[c] + " ", " "); }​ 

And replace won't remove anything if the matching substring does not exist.

like image 191
VisioN Avatar answered Nov 07 '22 13:11

VisioN