Skip to content

Instantly share code, notes, and snippets.

@boazsender
Created July 16, 2010 05:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save boazsender/477970 to your computer and use it in GitHub Desktop.
Save boazsender/477970 to your computer and use it in GitHub Desktop.
classList() method which provides the behaviour you would expect from a method implementation of the HTML5 classList property which is supported currently in FF 3.6
/*
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
$(selector).classList(['new', 'class', 'names']) //replaces the current element's classes
*/
jQuery.fn.extend({
classList: function( value ) {
if ( jQuery.isArray( value ) ) {
// An array was passed, join it into a string.
value = value.join(' ')
} else if ( value ) {
// A non array was passed (either a sing string or multiple stings),
// join them into a string single string.
value = 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', value );
}
});
@mathiasbynens
Copy link

You can check for native classList support as follows:

if (!!document.createElement('p').classList) {
 // native classList support
};

It could be a good idea to add this feature test to your plugin and just map $.fn.classList to the native implementation if it’s available.

@boazsender
Copy link
Author

The thing is, that classList is a token list property of the html element and this is a method of the jQuery collection, so mapping the method to the native implementation might not make sense. But i'm going to think about it.

@mathiasbynens
Copy link

You’re right, I should’ve looked more closely. Your jQuery classList does other stuff than HTML5 classList.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment