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).r
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).
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.
No, not necessary to check for removeClass()
.
Just use
$(this).removeClass("test");