Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a particular reason why jQuery's addClass() is not right-trimming?

<div id="myDiv" class=" blueberry mango "></div>

If we use the .addClass()

$("#myDiv").addClass("carrot");

The class for myDiv is now "(no-space)blueberry mango(double-space)carrot"

There is a left-trim, but there are double spaces between mango and carrot because there were no right-trim

  • Is there a particular reason why jQuery's addClass() is not right-trimming?
  • Or the left-trim was not even intended?
like image 852
ajax333221 Avatar asked Jan 04 '12 20:01

ajax333221


1 Answers

Seems like jQuery is doing the trim 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 it's like below,

jQuery.trim(" blueberry mango " + " " + "carrot")

like image 165
Selvakumar Arumugam Avatar answered Nov 15 '22 10:11

Selvakumar Arumugam