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")

I’ve done a quick demo in jsfiddle to demonstrate.

Optimised Version

Thanks Vlad.

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

Check this out on jsfiddle.

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.

Free Guide:

How to Choose the Right Charting Library for Your Application

How do you make sure that the charting library you choose has everything you need? Sign up to receive this detailed guide from FusionCharts, which explores all the factors you need to consider before making the decision.

  • Vladimir Kharlampidi

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

Special Offer
Free course!

Git into it! Bonus course Introduction to Git is yours when you take up a free 14 day SitePoint Premium trial.