jQuery
Web Development
Programming
Data Attributes
JavaScript

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.

javascript
1// Exact match
2$('[data-status="active"]');
3
4// Starts with
5$('[data-id^="user-"]');
6
7// Contains
8$('[data-tags*="featured"]');

How data-* attributes work

Any attribute prefixed with data- is valid HTML5. The browser ignores it for rendering and exposes it to JavaScript.

html
<div data-user-id="42" data-role="editor" data-active="true">
    Jane Doe
</div>

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

javascript
1// Select all elements with data-role="admin"
2$('[data-role="admin"]').css('background', '#ffe0e0');
3
4// Select all list items with data-category="electronics"
5$('li[data-category="electronics"]').addClass('highlight');

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:

javascript
1// Select everything that has a data-tooltip attribute
2$('[data-tooltip]').each(function () {
3    // Initialize tooltip behavior
4    $(this).on('mouseenter', function () {
5        console.log($(this).data('tooltip'));
6    });
7});

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:

OperatorMeaningExampleMatches
=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:

html
1<ul id="fileList">
2    <li data-file="report-2024.pdf">Annual Report</li>
3    <li data-file="logo.png">Company Logo</li>
4    <li data-file="slides-2024.pdf">Presentation</li>
5    <li data-file="avatar.jpg">Profile Photo</li>
6</ul>
javascript
1// Highlight all PDF files
2$('li[data-file$=".pdf"]').css('font-weight', 'bold');
3
4// Select all 2024 files
5$('li[data-file*="2024"]').addClass('current-year');

Combining conditions with AND and OR

Chained brackets are AND conditions:

javascript
1// Elements with data-role="admin" AND data-active="true"
2$('[data-role="admin"][data-active="true"]').show();
3
4// Table rows that are selected and not archived
5$('tr[data-selected="true"][data-archived!="true"]').css('background', '#e0ffe0');

For OR, use a comma (or the .add() method):

javascript
// Elements with data-priority="high" OR data-priority="critical"
$('[data-priority="high"], [data-priority="critical"]').addClass('alert');

.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:

javascript
1// Read the HTML attribute
2var userId = $('div').attr('data-user-id');
3
4// Write the HTML attribute (visible in DOM inspector)
5$('div').attr('data-user-id', '99');

.data() reads the attribute once, then caches the value in jQuery's internal store:

javascript
1// First call: reads from HTML attribute, converts types, and caches
2var userId = $('div').data('userId'); // Returns number 42, not string "42"
3
4// Subsequent writes go to the internal cache, NOT the HTML attribute
5$('div').data('userId', 99);
6// The DOM still shows data-user-id="42"
Behavior.attr('data-*').data()
Reads fromHTML attribute (always)Cache (or attribute on first read)
Writes toHTML attributeInternal jQuery cache only
Visible in DOM inspectorYesNo (after .data() write)
Attribute selectors see changesYesNo
Type conversionNo (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:

javascript
1// Delegate click events for data-action buttons
2$('#container').on('click', '[data-action]', function () {
3    var action = $(this).data('action');
4
5    switch (action) {
6        case 'edit':
7            console.log('Editing item', $(this).data('itemId'));
8            break;
9        case 'delete':
10            console.log('Deleting item', $(this).data('itemId'));
11            break;
12        case 'archive':
13            console.log('Archiving item', $(this).data('itemId'));
14            break;
15    }
16});
html
1<div id="container">
2    <button data-action="edit" data-item-id="1">Edit</button>
3    <button data-action="delete" data-item-id="1">Delete</button>
4    <!-- New buttons added dynamically will also work -->
5</div>

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:

javascript
1// Slower: searches entire DOM
2$('[data-role="widget"]');
3
4// Faster: searches only within #dashboard
5$('#dashboard').find('[data-role="widget"]');

And cache selections you reuse:

javascript
1var $widgets = $('#dashboard').find('[data-role="widget"]');
2
3// Reuse the cached selection
4$widgets.show();
5$widgets.addClass('loaded');

The same selectors in vanilla JavaScript

querySelectorAll accepts the same attribute selector syntax:

javascript
1// Select by data attribute with vanilla JS
2var admins = document.querySelectorAll('[data-role="admin"]');
3
4// Read data attribute
5admins.forEach(function (el) {
6    console.log(el.dataset.role); // "admin"
7});
8
9// Write data attribute (updates the DOM)
10admins.forEach(function (el) {
11    el.dataset.role = 'viewer';
12});

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.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No 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 course
Data 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.

Practice algorithms