Select elements by data attribute with jQuery
Codemia Knowledge Hub ·
Use the CSS attribute selector syntax: $('[data-role="admin"]') selects every element whose data-role equals admin. The partial match operators ^= (starts with), $= (ends with) and *= (contains) allow looser queries.
How data-* attributes work
Any attribute prefixed with data- is valid HTML5. The browser ignores it for rendering and exposes it to JavaScript.
An element can carry any number of data attributes. Names after data- should be lowercase and hyphenated. The browser normalizes them to camelCase in the dataset API, and jQuery handles both forms.
Matching an exact value
The tag before the bracket is optional. $('[data-role="admin"]') searches all elements, while $('li[data-role="admin"]') only searches <li> elements.
Matching any element that has the attribute
Leave out the = to select elements that have the attribute, whatever its value:
This suits progressive enhancement: add data-tooltip="some text" to any element, then initialize all tooltips with one selector.
Partial match operators
jQuery supports the CSS3 attribute substring selectors:
| Operator | Meaning | Example | Matches |
= | Exact match | $('[data-type="primary"]') | data-type="primary" |
^= | Starts with | $('[data-id^="user-"]') | data-id="user-42", data-id="user-abc" |
$= | Ends with | $('[data-file$=".pdf"]') | data-file="report.pdf" |
*= | Contains | $('[data-tags*="urgent"]') | data-tags="urgent,high", data-tags="not-urgent" |
!= | Not equal (jQuery extension) | $('[data-status!="deleted"]') | Everything except data-status="deleted" |
For example, given this list:
Combining conditions with AND and OR
Chained brackets are AND conditions:
For OR, use a comma (or the .add() method):
.data() vs .attr(): why selectors miss updated values
jQuery has two ways to work with data attributes, and they behave differently.
.attr() always reads and writes the HTML attribute:
.data() reads the attribute once, then caches the value in jQuery's internal store:
| Behavior | .attr('data-*') | .data() |
| Reads from | HTML attribute (always) | Cache (or attribute on first read) |
| Writes to | HTML attribute | Internal jQuery cache only |
| Visible in DOM inspector | Yes | No (after .data() write) |
| Attribute selectors see changes | Yes | No |
| Type conversion | No (always string) | Yes ("42" becomes 42, "true" becomes true) |
So if you update a value with .data('key', newValue) and then select $('[data-key="newValue"]'), nothing matches, because the HTML attribute never changed. Use .attr('data-key', newValue) when selectors need to see the new value.
Handling dynamically added elements
Use event delegation so elements added after page load work without re-binding:
This is the standard way to use data attributes as JavaScript hooks, rather than class names (which may change for CSS reasons) or IDs (too rigid for repeated elements).
Keeping attribute selectors fast
Attribute selectors are slower than ID or class selectors because the browser inspects each candidate's attributes. Usually the difference is negligible, but on pages with thousands of elements, scope the search to a container:
And cache selections you reuse:
The same selectors in vanilla JavaScript
querySelectorAll accepts the same attribute selector syntax:
dataset always reads and writes the HTML attribute directly, so it does not have the caching gotcha of jQuery's .data().
Mistakes with data attribute selectors
Writing with .data() and selecting by attribute. .data() writes to jQuery's cache, while attribute selectors query the DOM. Use .attr('data-*', value) instead.
Forgetting .data() converts types. "42" becomes the number 42 and "true" becomes the boolean true, so comparisons against the string attribute value can differ.
Not scoping selectors on large pages. $('[data-widget]') scans the whole document. Scope with .find().
Styling through data attributes. Data attributes are for JavaScript behavior, CSS classes are for styling. Mixing them makes the code harder to maintain.
Binding directly to elements that do not exist yet. This fails silently. Delegate from a parent that exists at bind time.
Related reading
- Self-references in object literals / initializers
- Send HTML emails with Python
- Sending command line arguments to npm script
- Sending html content in AWS SNSSimple Notification Service emails notifications
- Serializing to JSON in jQuery
- Set select option ''selected'', by value
- Set TextView text from html-formatted string resource in XML
- Set useState hook in a async loop
System design interview problems on this topic
- Design Google Doc: solution and walkthrough
- Design Facebook Messenger: solution and walkthrough
- Design Typeahead Suggestion: solution and walkthrough
- Design an Online Presence Indicator Service: solution and walkthrough
.png&w=3840&q=75)
Tackling System Design Interview Problems
A short course that equips you with the skills to approach system design interviews methodically.
Start the free courseNo course covers this one yet
Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.
Build my courseData Structures & Algorithms practice on Codemia
Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.