Created
March 25, 2012 11:56
-
-
Save cballou/2193128 to your computer and use it in GitHub Desktop.
The getMatchingClass plugin is useful for determing whether a singular matching element contains a particular <em><strong>partial class name</strong></em>. The idea behind the function is to allow for partial matching using a subset of jQuery selectors. h
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
| // example one - remove class if a match is found at the beginning | |
| $elem = $('#elemToMatch'); | |
| $.each($elem.getMatchingClass('*=classBeginsWith_'), function() { | |
| $elem.removeClass(this); | |
| }); | |
| // example two - perform an action if a match is found at the end | |
| // note this is not a very good method for showing and hiding | |
| // child elements and is only used as an example | |
| $('#elemToMatch').click(function() { | |
| var parent, match, $this = $(this); | |
| if (match = $this.getMatchingClass('$="_hideChildren"')) { | |
| parent = match.split('_')[0]; | |
| $this.removeClass(match).addClass(parent + '_showChildren').children('ul').fadeOut(200); | |
| } else if (match = $elem.getMatchingClass('$="_showChildren"')) { | |
| parent = match.split('_')[0]; | |
| $elem.removeClass(match).addClass(parent + '_showChildren').children('ul').fadeIn(200); | |
| } | |
| }); |
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
| $.fn.getMatchingClass = function(selector) { | |
| var regex, _class, tmp; | |
| tmp = $(this)[0].className; | |
| _class = selector; | |
| _class = _class.replace(/(^|*|$)?=/i, ''); | |
| _class = _class.replace(/"/g, ''); | |
| if (selector.indexOf('$=') != -1) { | |
| regex = new RegExp('[\s]+' + _class + '$', 'g'); | |
| } else if (selector.indexOf('^=') != -1) { | |
| regex = new RegExp('^' + _class + '[\s]+', 'g'); | |
| } else if (selector.indexOf('*=') != -1) { | |
| regex = new RegExp('[a-zA-z0-9_\-]*' + _class + '[a-zA-z0-9_\-]*', 'g'); | |
| } else if (selector.indexOf('=') != -1) { | |
| regex = new RegExp('^' + _class + '$', 'g'); | |
| } else return false; | |
| return tmp.match(regex); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment