Selecting element by data attribute with jQuery

$('*[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')).

Leave a Comment