Last active
August 22, 2017 17:08
-
-
Save jackfuchs/3583421f2b21553efb364868e8c17be0 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* 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