Is there any special reason why jQuery addClass () is not editing?
<div id="myDiv" class=" blueberry mango "></div>
If we use . addClass ()
$("#myDiv").addClass("carrot");
The class for myDiv
now "(no-space)blueberry mango(double-space)carrot"
There is left-trim
, but there are double spaces between mango and carrots because there was no right-trim
- Is there any special reason why jQuery
addClass()
not a right trim? - Or was the left trim not even intended?
JQuery seems to do the trimming after adding the class. See jquery addclass code below,
addClass: function( value ) { var classNames, i, l, elem, setClass, c, cl; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call(this, j, this.className) ); }); } if ( value && typeof value === "string" ) { classNames = value.split( rspace ); for ( i = 0, l = this.length; i < l; i++ ) { elem = this[ i ]; if ( elem.nodeType === 1 ) { if ( !elem.className && classNames.length === 1 ) { elem.className = value; } else { //HERE IS APPENDS ALL CLASS IT NEEDS TO ADD setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass ); } } } } return this; }
So, as shown below,
jQuery.trim(" blueberry mango " + " " + "carrot")
This is because jQuery adds the class to the list of classes, and then runs trim
for the entire line.
Check out the source for addClass
to see what happens.
Looking at the source, I assume that there is no reason for this:
setClass = " " + elem.className + " "; for ( c = 0, cl = classNames.length; c < cl; c++ ) { if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) { setClass += classNames[ c ] + " "; } } elem.className = jQuery.trim( setClass );
True, the presence of a space before and after each class helps to find whether there is a new class (added) or not, but still they can replace the first line:
setClass = " " + jQuery.trim(elem.className) + " ";
and still work the same ...