Linode
RSS 2.0 Feed
Posted on April 19th, 2010 at 07:07 AM by Corey Ballou

The getMatchingClass plugin is useful for determing whether a singular matching element contains a particular partial class name. The idea behind the function is to allow for partial matching using the following jQuery selectors:

  • $= – “ends with” selector
  • ^= – “starts with” selector
  • *= – “contains” selector
  • = – “matches” selector

The plugin is useful in the event you need to determine if an element contains a portion of a class name utilizing already known jQuery selectors. Unfortunately this functionality did not exist within the Sizzle selector engine. Improvements and bugfixes are always welcome.

Source Code

$.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);
}

Example Usage

// 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);
	}
});

To reiterate, this plugin is only useful in very specific cases. My initial use case involved handling a lightbox with class variances to allow for complete changes in styling.

Related Posts

Leave a Reply

Allowable tags
a, abbr, b, blockquote, cite, code, em, i, strike, strong, pre lang, line

* comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.