Tuesday, July 19, 2011

filterByData jQuery Plugin: Select by HTML5 Data Attr Value

I've been using HTML5 data attributes more and more lately and have been finding it slightly awkward when I need to select element based on their data.

I find myself writing the following code snippet more than once and I just doesn't feel right to me.

var valueImLookingFor = "myvalue";
//The string concatenation just feels wrong to me...
$( "p[data-mytype" + "='" + valueImLookingFor + "']" )
.doSomething();

I initially tweeting about my thoughts on this syntax and mentioned that I wished a better API existed. Instead of wishing, I figured the best route would be to figure something out on my own.

I ended up writing a jQuery plugin and then after talking with Doug Neiner (a jQuery team member) it morphed into the following plugin...

(function($) {
/* by Elijah Manor with collaboration from Doug Neiner
* Filter results by html5 data attributes either at
* design or at runtime
*
* Usages:
* $( "p" ).filterByData( "mytype" );
* $( "p" ).filterByData( "mytype, "mydata" );
*/
$.fn.filterByData = function( type, value ) {
return this.filter( function() {
var $this = $( this );
return value != null ?
$this.data( type ) === value :
$this.data( type ) != null;
});
};
})(jQuery);

I want to thank Paul Giberson for recommending to use the ternary operator which has the same behavior, but minifies to a much smaller output.

I wrote some unit tests for the plugin and you can view them here...



I also wanted to give a shout out to Dan Heberden (another jQuery team member) who saw my tweet and wrote a similar plugin to solve the same issue. Dan took a slightly different approach and performs a find and filter at the same time, where as my plugin only filters the initial selection.