views:

139

answers:

1

Is there an easy and straight-forward method to select elements based on their data attribute? For example, select all anchors that has data attribute named customerID which has value of 22. I am kind of hesitant to use rel or other attributes to store such information, but I find it much harder to select an element based on what data is stored in it.

Thanks!

+2  A: 
$('*[data-customerID=22]');

You should be able to omit the *, but IIRC, depending on which jQuery version you’re using, this might give faulty results.

Also, if you work with data attributes a lot in your jQuery scripts, you might want to consider using the HTML5 custom data attributes plugin. This allows you to write even more readable code by using .dataAttr('foo'), and results in a smaller file size after minification (compared to using .attr('data-foo')).

Mathias Bynens