Skip to content

Instantly share code, notes, and snippets.

@jackfuchs
Last active August 22, 2017 17:08
Show Gist options
  • Save jackfuchs/3583421f2b21553efb364868e8c17be0 to your computer and use it in GitHub Desktop.
Save jackfuchs/3583421f2b21553efb364868e8c17be0 to your computer and use it in GitHub Desktop.
/**
* jQuery.alterClass
*
* For altering classes
*
* @param removals (wildcards are possible)
* [@param] additions
* @return jQuery object
*
* @author Axel Jack Fuchs (Cologne, Germany)
* @date 01-03-2016 10:33
* @url https://gist.github.com/jackfuchs/3583421f2b21553efb364868e8c17be0
*
* Example
* Before: <div class="remove-foo-1 remove-foo-2 remove-bar"></div>
* Alter: $('div').alterClass('remove-foo-* remove-bar', 'add-foo add-bar');
* Result: <div class="add-foo add-bar"></div>
*/
$.fn.alterClass = function (removals, additions) {
var self = this;
if (removals.indexOf('*') === -1) {
self.removeClass(removals);
return !additions ? self : self.addClass(additions);
}
var patt = new RegExp('\\s'+ removals.replace(/\*/g, '[A-Za-z0-9-_]+').split(' ').join('\\s|\\s') +'\\s', 'g');
self.each(function (i, it) {
var cn = ' '+ it.className +' ';
while (patt.test(cn)) {
cn = cn.replace(patt, ' ');
}
it.className = $.trim(cn);
});
return !additions ? self : self.addClass(additions);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment