Skip to content

Instantly share code, notes, and snippets.

@noonat
Created May 12, 2010 18:49
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 noonat/398973 to your computer and use it in GitHub Desktop.
Save noonat/398973 to your computer and use it in GitHub Desktop.
jQuery replace classes
// Removes all classes beginning with prefix, and replaces them
// with a prefix+suffix class. For example:
// $('#blah').addClass('foobaz');
// $('#blah').replaceClasses('foo', 'baz');
jQuery.fn.replaceClasses = function(prefix, suffix) {
var re = new RegExp('^' + prefix);
return this.each(function() {
var classes = this.className.split(/\s+/);
var newClasses = [];
var i = classes.length;
while (i--) {
if (!re.test(classes[i])) {
newClasses.push(classes[i]);
}
}
newClasses.push(prefix + suffix);
this.className = newClasses.join(' ');
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment