No, no problem. What the function removeClass
is basically analyzing the value of the attribute class
of the element as string and replace all occurrences of the specified class with a blank space. If the element does not have the class, nothing will be replaced and the value will remain intact.
View function implementation (source):
function (value) {
var classes, elem, cur, curValue, clazz, j, finalValue, i = 0;
if (isFunction(value)) {
return this.each(function (j) {
jQuery(this).removeClass(value.call(this, j, getClass(this)));
});
}
if (!arguments.length) {
return this.attr("class", "");
}
classes = classesToArray(value);
if (classes.length) {
while ((elem = this[i++])) {
curValue = getClass(elem);
// This expression is here for better compressibility (see addClass)
cur = elem.nodeType === 1 && (" " + stripAndCollapse(curValue) + " ");
if (cur) {
j = 0;
while ((clazz = classes[j++])) {
// Remove *all* instances
while (cur.indexOf(" " + clazz + " ") > -1) {
cur = cur.replace(" " + clazz + " ", " ");
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = stripAndCollapse(cur);
if (curValue !== finalValue) {
elem.setAttribute("class", finalValue);
}
}
}
}
return this;
}
Basically what interests us right now is the excerpt:
if (cur) {
j = 0;
while ((clazz = classes[j++])) {
// Remove *all* instances
while (cur.indexOf(" " + clazz + " ") > -1) {
cur = cur.replace(" " + clazz + " ", " ");
}
}
// Only assign if different to avoid unneeded rendering.
finalValue = stripAndCollapse(cur);
if (curValue !== finalValue) {
elem.setAttribute("class", finalValue);
}
}
Where it traverses all classes indicated in the function parameter:
while ((clazz = classes[j++])) {
...
}
And for each class remove all occurrences by replacing them with a blank:
// Remove *all* instances
while (cur.indexOf(" " + clazz + " ") > -1) {
cur = cur.replace(" " + clazz + " ", " ");
}
If the element does not have the class, the condition cur.indexOf(" " + clazz + " ") > -1
is not satisfied and the value of cur
will remain intact in this way, finalValue
will equal the curValue
and there will be no change in the attribute class
.
if (curValue !== finalValue) {
elem.setAttribute("class", finalValue);
}
No problem even in jQuery (example case of the question), nor in pure JS.
– bfavaretto