Html – Selecting element by data attribute with jQuery

custom-data-attributehtmljquery

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.

Best Answer

$('*[data-customerID="22"]');

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

Note that for compatibility with the Selectors API (document.querySelector{,all}), the quotes around the attribute value (22) may not be omitted in this case.

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')).