jQuery
Web Development
Programming
Data-Attribute
Element Selection

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:

html
1<ul id="user-list">
2  <li data-role="admin" data-id="1">Alice</li>
3  <li data-role="editor" data-id="2">Bob</li>
4  <li data-role="admin" data-id="3">Carol</li>
5  <li data-role="viewer" data-id="4">Dave</li>
6</ul>
javascript
1// Select all admin users
2var admins = $('[data-role="admin"]');
3console.log(admins.length); // 2
4
5// Select by data-id
6var user = $('[data-id="3"]');
7console.log(user.text()); // "Carol"

Chain selectors to require several attributes at once:

javascript
// Elements with both data-role="admin" AND data-id="1"
var adminAlice = $('[data-role="admin"][data-id="1"]');

Elements that have a data attribute with any value

Leave out the value to match any element that has the attribute:

javascript
// All elements with a data-role attribute
var allWithRole = $('[data-role]');

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:

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

html
<div data-tags="urgent,review">Task 1</div>
<div data-tags="review,low">Task 2</div>
<div data-tags="urgent,critical">Task 3</div>
javascript
1// All elements whose tags contain "urgent"
2var urgentTasks = $('[data-tags*="urgent"]');
3console.log(urgentTasks.length); // 2
4
5// Elements whose tags start with "review"
6var reviewFirst = $('[data-tags^="review"]');
7console.log(reviewFirst.length); // 1

*= 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():

html
<div class="product" data-price="29.99" data-stock="150">Widget A</div>
<div class="product" data-price="49.99" data-stock="3">Widget B</div>
<div class="product" data-price="9.99" data-stock="0">Widget C</div>
javascript
1// Products priced over $20 that are in stock
2var affordable = $('.product').filter(function() {
3    var price = parseFloat($(this).data('price'));
4    var stock = parseInt($(this).data('stock'), 10);
5    return price > 20 && stock > 0;
6});
7
8console.log(affordable.length); // 2 (Widget A and Widget B)

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

html
<button id="counter" data-count="3" data-active="true">Click</button>
javascript
1var btn = $('#counter');
2
3// Attribute access (always strings)
4console.log(btn.attr('data-count'));   // "3" (string)
5console.log(btn.attr('data-active')); // "true" (string)
6
7// .data() access (type coercion)
8console.log(btn.data('count'));   // 3 (number)
9console.log(btn.data('active')); // true (boolean)

The behavior that catches people:

javascript
1// This updates jQuery's internal cache but NOT the DOM attribute
2btn.data('count', 10);
3
4// The attribute selector still sees the original DOM value
5console.log($('[data-count="10"]').length); // 0
6console.log($('[data-count="3"]').length);  // 1
7
8// .data() sees the updated value
9console.log(btn.data('count')); // 10

If attribute selectors (or CSS) need to see the new value, set it with .attr() instead of .data():

javascript
btn.attr('data-count', 10);
console.log($('[data-count="10"]').length); // 1

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:

javascript
1// Simple case: known-safe values
2function findByRole(role) {
3    return $('[data-role="' + role + '"]');
4}
5
6// Template literal version
7function findByRole(role) {
8    return $(`[data-role="${role}"]`);
9}

If the value might contain quotes, brackets or other special characters, compare in .filter() instead:

javascript
1// Safe for any value, including quotes and special characters
2function findByRoleSafe(role) {
3    return $('[data-role]').filter(function() {
4        return $(this).data('role') === role;
5    });
6}

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:

javascript
1// Instead of searching the whole document
2var row = $('[data-user-id="42"]');
3
4// Scope to a container
5var row = $('#users-table').find('[data-user-id="42"]');

This matters most inside loops, scroll handlers and other hot paths.

Combining with element, class and ID selectors

javascript
1// Only div elements with data-visible="true"
2$('div[data-visible="true"]')
3
4// Elements with class "card" and data-status="active"
5$('.card[data-status="active"]')
6
7// Direct children of #container with data-priority
8$('#container > [data-priority]')
9
10// Input elements with a specific data attribute
11$('input[data-validate="email"]')

Vanilla JavaScript equivalents

Without jQuery, the native APIs are:

javascript
1// querySelector (first match)
2document.querySelector('[data-role="admin"]');
3
4// querySelectorAll (all matches)
5document.querySelectorAll('[data-role="admin"]');
6
7// Reading data attributes natively
8var el = document.querySelector('[data-role="admin"]');
9console.log(el.dataset.role); // "admin" (always a string)

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"]').

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