Created
May 12, 2010 18:49
-
-
Save noonat/398973 to your computer and use it in GitHub Desktop.
jQuery replace classes
This file contains 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
// 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