jQuery: select elements that have specific styles defined in the CSS

JavaScript can access the CSS rules contained in a stylesheet very easily. Each rule is made up of two components: a selector and the CSS declarations. Knowing this, we can use jQuery to select an element only when it has some specific CSS styles attached to it.

Consider the following CSS styles:


#test {
	color: green;
}

We can access the above rule as follows:


var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
for( var i = 0; i < rules.length; ++i ) {
	var selector = rules[i].selectorText; // #test
	var css = rules[i].cssText; // #test { color: green; }
}

The selector expression is contained in the selectorText property of each rule object while the whole rule expression can be accessed through the cssText property.

Now suppose that we want to select an element only when it has the transition property specified on it. We can create a custom jQuery selector like the following.


$.expr[ ":" ].hasTransition = function( element ) {
		var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
		var found = false;
		for( var i = 0; i < rules.length; ++i ) {
			var selector = rules[i].selectorText;
			var css = rules[i].cssText;
			if( css.indexOf( "transition:" ) != -1 ) { // use a regular expression here
				var $element = $( element );
				var $selector = $( selector );
				if( $element.get( 0 ) === $selector.get( 0 ) ) { // same element?
					found = true;
				}
			}
		}

		return found;
			
};

We've simply turned the original CSS selector expression into a jQuery object and compared the newly created object with the element we want to select. The comparison must always be performed between two DOM elements.

Before checking whether both elements are the same, we have to run a simple pattern matching against the cssText property. For the sake of the example, I've used here the indexOf() method, but you should always use a robust regular expression.

[view-example url="http://codepen.io/gabrieleromanato/pen/CLtwb"]
Back to top