Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Selecting element by data attribute with jQuery

Is there a simple and direct technique to choose elements dependent on their data attribute? For instance, select all anchors that have an information property named customerID which has a value of 22.
by

2 Answers

aashaykumar

$('[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')).
RoliMishra
It may work

var elements = document.querySelectorAll('[data-customerID="22"]');
elements[0].innerHTML = 'it worked!';


<a data-customerID='22'>test</a>

Login / Signup to Answer the Question.