Skip to content

Instantly share code, notes, and snippets.

@barneycarroll
Created June 12, 2014 11:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save barneycarroll/b4f913de9e95566e6806 to your computer and use it in GitHub Desktop.
Save barneycarroll/b4f913de9e95566e6806 to your computer and use it in GitHub Desktop.
Sometimes Sizzle + CSS level 3's attribute selector logic isn't enough. Sometime you want to be able to do a RegExp search of attribute names, other times you don't know what the attribute name is but have some inkling as to the value. Not recommended for production (this is a performance-intensive anti-pattern) — this was written to help debug …
// Accessible from $ (whole document scope) or on $.fn (search with jQuery scope)
// Usage:
// attributeMatch( name, value, returnAttributes )
//
// Where @name and @value are RegExps or RegExps-as-strings to match against attributes names and values.
// @returnAttributes returns the attributes themselves rather than the owner element - useful to avoid repeating yourself
// eg: $.attributeMatch( /^lang$/, null, true )[ 0 ].value;
//
// To return all elements with ARIA attributes:
// $.attributeMatch( '^aria-\w+' );
//
// To filter current set of attributes whose value contains the word 'off', and return those attributes:
// $( ':input' ).attributeMatch( null, /\boff\b/, true );
void function configAttributeMatch(){
$.attributeMatch = $.fn.attributeMatch = function getElementsMatchingAttributes( name, value, returnAttributes ){
var attributes = getAttributes.apply( this, _.toArray( arguments ) );
return returnAttributes ? attributes : getOwnerElements( attributes );
};
function getAttributes( name, value ){
var scope = ( this instanceof jQuery ? this : $( '*' ) ).get();
var properties = {};
if( name ) properties.name = name;
if( value ) properties.value = value;
var attributeList = _( scope )
.pluck( 'attributes' )
.map( function iterateAttributeLists( attributes ){
return _.filter( attributes, function doesAttributeMatch( attribute ){
return _.every( properties, function testProperty( expression, property ){
return !expression || ( new RegExp( expression ) ).test( attribute[ property ] );
} );
} );
} )
.reject( function( x ){ return _.isEmpty( x ); } )
.flatten()
.valueOf();
return attributeList;
}
function getOwnerElements( attributeList ){
return $( _.pluck( attributeList, 'ownerElement' ) );
}
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment