Skip to main content
1 of 4
bPratik
  • 7k
  • 4
  • 40
  • 70

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 
bPratik
  • 7k
  • 4
  • 40
  • 70