Skip to content

Instantly share code, notes, and snippets.

@tacomanator
Forked from noonat/jquery.replaceClasses.js
Created June 23, 2013 23:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tacomanator/5846895 to your computer and use it in GitHub Desktop.
Save tacomanator/5846895 to your computer and use it in GitHub Desktop.
// 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