jQuery Filter Objects by Data Attribute Value

Sam Deering
Tweet

How you might use jQuery to filter elements by their data Attribute values. This code snippet grabs all divs that have an id beginning with “proto_” and have a data attribute of “state” with value “open”.

var $el = $('div[id^=proto_]').filter(function()
{
     return ($(this).data("state") == "open")
});
console.log($el);

I’ve done a quick demo in jsfiddle to demonstrate. http://jsfiddle.net/qgwnY/

Optimised Version

Thanks Vlad.

var $el = $('div[id^=proto_]').filter('div[data-state=open]').css('color','red');‚Äč

Check this out on jsfiddle.

Get your free chapter of Level Up Your Web Apps with Go

Get a free chapter of Level Up Your Web Apps with Go, plus updates and exclusive offers from SitePoint.

  • http://www.facebook.com/vladimir.kharlampidi Vladimir Kharlampidi

    Don’ forget that you can get the same result by using just:
    var $el = $(‘div[data-state=open]’) ;)