jQuery: find an element by data attribute value
Codemia Knowledge Hub ·
To find an element by a data-* attribute in jQuery, use an attribute selector: $('[data-role="admin"]'). It selects every element whose data-role attribute exactly equals "admin". Contains, starts-with and ends-with operators handle partial matches, and for logic such as numeric comparison you select broadly and narrow with .filter().
Exact match with an attribute selector
Given this markup:
Chain selectors to require several attributes at once:
Elements that have a data attribute with any value
Leave out the value to match any element that has the attribute:
This is handy for initializing components that use data attributes as configuration markers.
Partial match operators
jQuery supports the CSS attribute selector operators for substring matching:
| Operator | Meaning | Example |
= | Exact match | $('[data-type="primary"]') |
*= | Contains substring | $('[data-tags*="urgent"]') |
^= | Starts with | $('[data-path^="/api"]') |
$= | Ends with | $('[data-file$=".pdf"]') |
~= | Contains word (space-separated) | $('[data-classes~="active"]') |
!= | Not equal (jQuery extension) | $('[data-status!="archived"]') |
For example:
*= is plain substring matching, not word matching: $('[data-tags*="ur"]') also matches elements containing "urgent".
Numeric and multi-condition checks with .filter()
Attribute selectors only do string comparisons. For numbers, boolean logic or several conditions, use .filter():
The broad selector (.product) stays simple and the filtering logic stays readable.
Attribute selectors vs. the .data() API
These are related but not the same, and mixing them up is the most common jQuery data-attribute mistake.
Attribute selectors search the DOM by the literal HTML attribute value and always deal in strings.
.data() reads jQuery's internal data cache. It coerces types (numbers, booleans, JSON objects) and reflects values set in code with .data('key', value).
The behavior that catches people:
If attribute selectors (or CSS) need to see the new value, set it with .attr() instead of .data():
Building selectors from variables safely
When the value comes from a variable or user input, string-built selectors can break on special characters or be injected into:
If the value might contain quotes, brackets or other special characters, compare in .filter() instead:
This avoids selector syntax errors and selector injection.
Scoping the search for performance
On large pages, searching the whole DOM for every query adds up. Scope to a container:
This matters most inside loops, scroll handlers and other hot paths.
Combining with element, class and ID selectors
Vanilla JavaScript equivalents
Without jQuery, the native APIs are:
Native dataset behaves like jQuery's .attr(), not .data(): it always returns strings and reflects DOM changes immediately.
Mistakes to avoid
- Treating
.data('name')and[data-name="value"]as interchangeable. The selector finds elements;.data()reads a value from an element you already selected. - Setting values with
.data()and expecting attribute selectors to find them..data()updates the cache, not the DOM. Use.attr('data-name', value)when the DOM must change. - Expecting numeric comparison from selectors. "Greater than 30" cannot be written as a
[data-age]selector; use.filter()with parsed values. - Interpolating untrusted input into selectors. Quotes and brackets can break the selector or cause unexpected matches.
- Leaving the value unquoted, as in
$('[data-count=3]'). It works for simple numbers but breaks on spaces or special characters. Write$('[data-count="3"]').
Related reading
- jQuery UI Sortable, then write order into a database
- jQuery's jquery-1.10.2.min.map is triggering a 404 (Not Found)
- JS How to track errors where there are many functions calls
- JS Repeated string Hackerrank Challenge
- JS what's the promises equivalent of async.each?
- JSLint is suddenly reporting Use the function form of use strict
- JSON datetime between Python and JavaScript
- kafka-node ready event is not getting triggered
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.