-
-
Save cowboy/478502 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Usages: | |
$(selector).classList() //returns an array of classnames | |
$(selector).classList('newclass') //replaces the current element's classes | |
$(selector).classList(['new', 'class', 'names']) //replaces the current element's classes | |
*/ | |
jQuery.fn.classList = function( classNames ) { | |
if ( jQuery.isArray( classNames ) ) { | |
// An array was passed, join it into a string. | |
classNames = classNames.join(' ') | |
} else if ( classNames ) { | |
// Individual arguments were passed, join them into a string. | |
classNames = Array.prototype.join.call( arguments, ' ' ); | |
} else { | |
// No arguments were passed, return an array of class names. | |
return this.attr( 'class' ).split( /\s+/ ); | |
} | |
// Set class names and return the original jQuery object. | |
return this.attr( 'class', classNames ); | |
}; |
It's a common metaphor for jQuery methods to work as both setters and getters, this behavior is the same as other jQuery collection methods like .attr() or .html() or .text().
(some people like it, some people don't, but at least it's consistent)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think it's odd to return different data types depending on if it's reading or writing. Also
jQuery.fn.classNames
might be more descriptive if it can both set and get.