Created
December 24, 2011 12:49
-
-
Save peteboere/1517285 to your computer and use it in GitHub Desktop.
jQuery alterClass plugin: Remove element classes with wildcard matching. Optionally add 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
/** | |
* jQuery alterClass plugin | |
* | |
* Remove element classes with wildcard matching. Optionally add classes: | |
* $( '#foo' ).alterClass( 'foo-* bar-*', 'foobar' ) | |
* | |
* Copyright (c) 2011 Pete Boere (the-echoplex.net) | |
* Free under terms of the MIT license: http://www.opensource.org/licenses/mit-license.php | |
* | |
*/ | |
(function ( $ ) { | |
$.fn.alterClass = function ( removals, additions ) { | |
var self = this; | |
if ( removals.indexOf( '*' ) === -1 ) { | |
// Use native jQuery methods if there is no wildcard matching | |
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 ); | |
}; | |
})( jQuery ); |
正是我需要的
Saved a lot of my time, thanks 😍
Great work man. and simple yet fast solution. Thanks! 👍
thanks 👍
This is nice bro .. thanks
This works beautifully... thank you very much, I truly appreciate it. 🙏🏼
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Saved my time... Thank you!