Skip to main content

Bug Tracker

Side navigation

#10623 closed bug (invalid)

Opened October 31, 2011 09:02PM UTC

Closed November 01, 2011 07:39PM UTC

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

Reported by: jquery@sameprecision.org Owned by: rwaldron
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;
Attachments (0)
Change History (4)

Changed October 31, 2011 09:37PM UTC by rwaldron comment:1

component: unfiledattributes
milestone: None1.next
owner: → rwaldron
priority: undecidedlow
status: newassigned

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

Changed November 01, 2011 01:45AM UTC by jquery@sameprecision.org comment:2

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;
}

Changed November 01, 2011 02:03PM UTC by rwaldron comment:3

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.

Changed November 01, 2011 07:39PM UTC by timmywil comment:4

resolution: → invalid
status: assignedclosed

Actually, it does check for dupes in that case.

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