Skip to content

Instantly share code, notes, and snippets.

@adam-lynch
Last active December 16, 2015 21:40
Show Gist options
  • Save adam-lynch/5501843 to your computer and use it in GitHub Desktop.
Save adam-lynch/5501843 to your computer and use it in GitHub Desktop.
A jQuery function which returns a subset of the given element(s) (jQuery object), where each element returned has the data attribute specified and thatdata attribute's value is equal to that of the second parameter (if one was given)
/**
* @param dataAttributeName string
* @param desiredDataAttributeValue string (optional)
* (desiredDataAttributeValue must be a string, strict comparison is done with data attribute value)
*
* @author: adam-lynch
*/
$.fn.filterByDataAttribute = function(dataAttributeName, desiredDataAttributeValue){
return $(this).filter(function() {
return desiredDataAttributeValue && $(this).data(dataAttributeName) === desiredDataAttributeValue
|| !desiredDataAttributeValue && $(this).is('*[data-'+dataAttributeName+']');
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment