user917670
user917670

Reputation: 871

Should hasClass precede removeClass - 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?

Upvotes: 35

Views: 6987

Answers (3)

wereHamster
wereHamster

Reputation: 487

At least for Chrome, it is useful to add a hasClass() check before removeClass(), because jQuery unconditionally assigns elem.className to the new string even if the string hasn't changed, which causes Chrome to invalidate and recalculate the layout.

One could argue that this is a bug in Chrome and it should check whether the className has actually changed from the previous value. However, it could also be that the browser has to recalculate the layout due to some obscure requirements that are written somewhere deep in the html spec.

I haven't tested Firefox. The Safari web inspector is useless as it won't tell you why the layout was invalidated/recalculated (which javascript function caused it).

Upvotes: 6

VisioN
VisioN

Reputation: 145438

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.

Upvotes: 39

thecodeparadox
thecodeparadox

Reputation: 87073

No, not necessary to check for removeClass().

Just use

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

Upvotes: 3

Related Questions