JavaScript
Article

jQuery Filter Objects by Data Attribute Value

By Sam Deering

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. https://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.

Sam Deering
Meet the author
Sam Deering is a Front-end Web Developer who specialises in JavaScript & jQuery. Sam is driven and passionate about sharing his knowledge to educate others.
  • 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]’) ;)

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.