diff options
author | Timmy Willison <4timmywil@gmail.com> | 2018-01-02 16:45:10 -0500 |
---|---|---|
committer | Timmy Willison <4timmywil@gmail.com> | 2018-01-08 11:43:53 -0500 |
commit | 80f57f8a13debaab87b99f73631669699da3e1a5 (patch) | |
tree | e89842f0becc28188d0d95142fe5d5ac2c30eb90 /src | |
parent | a88b48eab1cdbb9dac05679a0d1c0edd7cc4afd7 (diff) | |
download | jquery-80f57f8a13debaab87b99f73631669699da3e1a5.tar.gz jquery-80f57f8a13debaab87b99f73631669699da3e1a5.zip |
Attributes: allow array param in add/remove/toggleClass
+30 bytes instead of +182
Thanks to @faisaliyk for the first pass on this feature.
Fixes gh-3532
Close gh-3917
Diffstat (limited to 'src')
-rw-r--r-- | src/attributes/classes.js | 27 |
1 files changed, 19 insertions, 8 deletions
diff --git a/src/attributes/classes.js b/src/attributes/classes.js index 23b4cd6af..1c75821b2 100644 --- a/src/attributes/classes.js +++ b/src/attributes/classes.js @@ -12,6 +12,16 @@ function getClass( elem ) { return elem.getAttribute && elem.getAttribute( "class" ) || ""; } +function classesToArray( value ) { + if ( Array.isArray( value ) ) { + return value; + } + if ( typeof value === "string" ) { + return value.match( rnothtmlwhite ) || []; + } + return []; +} + jQuery.fn.extend( { addClass: function( value ) { var classes, elem, cur, curValue, clazz, j, finalValue, @@ -23,9 +33,9 @@ jQuery.fn.extend( { } ); } - if ( typeof value === "string" && value ) { - classes = value.match( rnothtmlwhite ) || []; + classes = classesToArray( value ); + if ( classes.length ) { while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); cur = elem.nodeType === 1 && ( " " + stripAndCollapse( curValue ) + " " ); @@ -64,9 +74,9 @@ jQuery.fn.extend( { return this.attr( "class", "" ); } - if ( typeof value === "string" && value ) { - classes = value.match( rnothtmlwhite ) || []; + classes = classesToArray( value ); + if ( classes.length ) { while ( ( elem = this[ i++ ] ) ) { curValue = getClass( elem ); @@ -96,9 +106,10 @@ jQuery.fn.extend( { }, toggleClass: function( value, stateVal ) { - var type = typeof value; + var type = typeof value, + isValidValue = type === "string" || Array.isArray( value ); - if ( typeof stateVal === "boolean" && type === "string" ) { + if ( typeof stateVal === "boolean" && isValidValue ) { return stateVal ? this.addClass( value ) : this.removeClass( value ); } @@ -114,12 +125,12 @@ jQuery.fn.extend( { return this.each( function() { var className, i, self, classNames; - if ( type === "string" ) { + if ( isValidValue ) { // Toggle individual class names i = 0; self = jQuery( this ); - classNames = value.match( rnothtmlwhite ) || []; + classNames = classesToArray( value ); while ( ( className = classNames[ i++ ] ) ) { |