Created
July 27, 2012 22:13
-
-
Save jessebeach/3190717 to your computer and use it in GitHub Desktop.
supplantClass jQuery plugin
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
| /** | |
| * 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