I improved upon psycho brm's filterByData extension to jQuery.
Where the former extension searched on a key-value pair, with this extension you can additionally search for the presence of a data attribute, irrespective of its value.
(function ($) { $.fn.filterByData = function (prop, val) { var $self = this; if (typeof val === 'undefined') { return $self.filter( function () { return typeof $(this).data(prop) !== 'undefined'; } ); } return $self.filter( function () { return $(this).data(prop) == val; } ); }; })(window.jQuery); Usage:
$('<b>').data('x', 1).filterByData('x', 1).length // output: 1 $('<b>').data('x', 1).filterByData('x').length // output: 1 // test data function extractData() { log('data-prop=val ...... ' + $('div').filterByData('prop', 'val').length); log('data-prop .......... ' + $('div').filterByData('prop').length); log('data-random ........ ' + $('div').filterByData('random').length); log('data-test .......... ' + $('div').filterByData('test').length); log('data-test=anyval ... ' + $('div').filterByData('test', 'anyval').length); } $(document).ready(function() { $('#b5').data('test', 'anyval'); }); // the actual extension (function($) { $.fn.filterByData = function(prop, val) { var $self = this; if (typeof val === 'undefined') { return $self.filter( function() { return typeof $(this).data(prop) !== 'undefined'; }); } return $self.filter( function() { return $(this).data(prop) == val; }); }; })(window.jQuery); //just to quickly log function log(txt) { if (window.console && console.log) { console.log(txt); //} else { // alert('You need a console to check the results'); } $("#result").append(txt + "<br />"); } #bPratik { font-family: monospace; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="bPratik"> <h2>Setup</h2> <div id="b1" data-prop="val">Data added inline :: data-prop="val"</div> <div id="b2" data-prop="val">Data added inline :: data-prop="val"</div> <div id="b3" data-prop="diffval">Data added inline :: data-prop="diffval"</div> <div id="b4" data-test="val">Data added inline :: data-test="val"</div> <div id="b5">Data will be added via jQuery</div> <h2>Output</h2> <div id="result"></div> <hr /> <button onclick="extractData()">Reveal</button> </div> Or the fiddle: http://jsfiddle.net/PTqmE/46/