Skip to content

Instantly share code, notes, and snippets.

@cowboy
Forked from boazsender/jQuery.classList.js
Created July 16, 2010 15:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save cowboy/478502 to your computer and use it in GitHub Desktop.
Save cowboy/478502 to your computer and use it in GitHub Desktop.
/*
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 );
};
@gf3
Copy link

gf3 commented Jul 16, 2010

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.

@cowboy
Copy link
Author

cowboy commented Jul 16, 2010

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