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.
For this to work in Chrome the value must not have another pair of quotes.
It only works, for example, like this:
I haven't seen a JavaScript answer without jQuery. Hopefully it helps someone.
Info:
data attributes
.querySelectorAll();
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')
).To select all anchors with the data attribute
data-customerID==22
, you should include thea
to limit the scope of the search to only that element type. Doing data attribute searches in a large loop or at high frequency when there are many elements on the page can cause performance issues.Native JS Examples
Get NodeList of elements
html:
<div data-id="container"></div>
Get the first element
html:
<div id="container"></div>
Target a collection of nodes which returns a nodelist
html:
Get elements based on multiple (OR) data values
html:
Get elements based on combined (AND) data values
html:
Get items where the value starts with
Just to complete all the answers with some features of the 'living standard' - By now (in the html5-era) it is possible to do it without an 3rd party libs:
document.querySelector('[data-answer="42"],[type="submit"]')
document.querySelectorAll('[data-answer="42"],[type="submit"]')
[data-answer="42"],[type="submit"]
[data-answer]
orinput[type]