Skip to content

Instantly share code, notes, and snippets.

@jessebeach
Created July 27, 2012 22:13
Show Gist options
  • Save jessebeach/3190717 to your computer and use it in GitHub Desktop.
Save jessebeach/3190717 to your computer and use it in GitHub Desktop.
supplantClass jQuery plugin
/**
* supplantClass() jQuery plugin
*
* Adds the replacement class string to each element.
*
* If a class or classes contain the needle, they are removed from the element.
*/
(function ($) {
// Add the plugin as a property of the jQuery fn object.
$.fn['supplantClass'] = function (needle, replacement) {
return this.each(function (index, element) {
var $this = $(this);
var cl = [];
// Get an array of classes the excludes any that contain the needle.
var classes = $this.attr('class').split(' ');
for (var i = 0; i < classes.length; i++) {
if (classes[i].indexOf(needle) === -1) {
cl.push(classes[i]);
}
}
// Push the replacement in all cases.
$.merge(cl, replacement.split(' '));
// Create a string and assign it to the object.
$this.removeAttr('class').addClass(cl.join(' '));
});
};
}(jQuery));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment