I find myself writing the following code snippet more than once and I just doesn't feel right to me.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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.