Bug Tracker

Opened 8 years ago

Closed 8 years ago

#10623 closed bug (invalid)

.addClass/.removeClass has inconsistent behavior when using space-separated classnames

Reported by: jquery@… Owned by: Rick Waldron
Priority: low Milestone: 1.next
Component: attributes Version: 1.6.4
Keywords: Cc:
Blocked by: Blocking:

Description

//example
var d = $("<div />").text("test").appendTo("body");
d.addClass("a a");

d.removeClass("a");

d.hasClass("a") == true;


//example
var d = $("<div />").text("test").appendTo("body");
d.addClass("a");
d.addClass("a");

d.removeClass("a");

d.hasClass("a") == false;

Change History (4)

comment:1 Changed 8 years ago by Rick Waldron

Component: unfiledattributes
Milestone: None1.next
Owner: set to Rick Waldron
Priority: undecidedlow
Status: newassigned

While I definitely say "Don't add two of the same class", I'll patch this, but priority is low.

comment:2 Changed 8 years ago by jquery@…

Easy fix. In addClass, if elem.className == "", className string parameter is assigned to elem.className without checking for dupes. This fix also works for addClass taking a callback parameter.

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 ) {
//begin fix
				setClass = " " + elem.className ? elem.className + " " : "";

				for ( c = 0, cl = classNames.length; c < cl; c++ ) {
					if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
						setClass += classNames[ c ] + " ";
					}
				}
				elem.className = jQuery.trim( setClass );
//end
			}
		}
	}

	return this;
}

comment:3 Changed 8 years ago by Rick Waldron

It's not a matter of being easy or not, of course it's easy, ut you're asking for a patch to correct a behaviour caused by you code mis-using the API.

comment:4 Changed 8 years ago by timmywil

Resolution: invalid
Status: assignedclosed

Actually, it does check for dupes in that case.

http://jsfiddle.net/timmywil/ARsyE/1/

Note: See TracTickets for help on using tickets.