(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);
pavlov.specify.globalApi = true;
pavlov.specify( "filterByData jQuery Plugin", function() {
var $fixture = $( "#qunit-fixture" );
describe( "Design-time Checks", function() {
it( "should match an element that has no value", function() {
var $p = $( "<p data-mytype></p>" ).appendTo( $fixture )
.filterByData( "mytype" );
assert( $p ).isDefined();
assert( $p.length ).isEqualTo( 1 );
});
it( "should match an element that is an empty string", function() {
var $p = $( "<p data-mytype=''></p>" ).appendTo( $fixture )
.filterByData( "mytype" );
assert( $p ).isDefined();
assert( $p.length ).isEqualTo( 1 );
});
it( "should match an element that has a non-empty value", function() {
var $p = $( "<p data-mytype='test'></p>" ).appendTo( $fixture )
.filterByData( "mytype" );
assert( $p ).isDefined();
assert( $p.length ).isEqualTo( 1 );
});
it( "should match an element based on it's value", function() {
var $p = $( "<p data-mytype='test1'></p>" +
"<p data-mytype='test2'></p>" )
.appendTo( $fixture )
.filterByData( "mytype", "test1" );
assert( $p ).isDefined();
assert( $p.length ).isEqualTo( 1 );
});
it( "should support popping off the stack", function() {
var $p = $( "<p data-mytype='test1'></p>" +
"<p data-mytype='test2'></p>" )
.appendTo( $fixture )
.filterByData( "mytype", "test1" )
.end();
assert( $p ).isDefined();
assert( $p.length ).isEqualTo( 2 );
});
});
describe( "Run-time Checks", function() {
it( "should match an element that a data-mytype was added as an empty string", function() {
var $p = $( "<p></p>" )
.data( "mytype", "" )
.appendTo( $fixture )
.filterByData( "mytype" );
assert( $p ).isDefined();
assert( $p.length ).isEqualTo( 1 );
});
it( "should match an element that a data-mytype was added as a non-empty string", function() {
var $p = $( "<p></p>" )
.data( "mytype", "test" )
.appendTo( $fixture )
.filterByData( "mytype" );
assert( $p ).isDefined();
assert( $p.length ).isEqualTo( 1 );
});
it( "should match an element that a data-mytype was added based on it's value", function() {
var $p = $( "<p></p>" )
.data( "mytype", "test" )
.appendTo( $fixture )
.filterByData( "mytype", "test" );
assert( $p ).isDefined();
assert( $p.length ).isEqualTo( 1 );
});
});
});
<h1 id="qunit-header"></h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
<div id="qunit-fixture"></div>