Explain Codes LogoExplain Codes Logo

Selecting element by data attribute with jQuery

javascript
prompt-engineering
best-practices
performance
Nikita BarsukovbyNikita Barsukov·Oct 4, 2024
TLDR

To select elements by data attribute in jQuery, use:

$('[data-attribute="value"]') // "Hello, element! You've been SELECTED!"

This line targets all elements where (dramatic drumroll) data-attribute equals value! Now you can sip your coffee knowing you've got the right elements!

To aim even more precisely at an a element with data-customerid="22":

$('a[data-customerid="22"]') // "The cake is a lie, the data attribute truth isn't!"

And your element is good to go for any jQuery action, like adding a class:

$('a[data-customerid="22"]').addClass('highlight'); // "Strut your stuff, .highlight!"

Fast and efficient; it feels like slicing warm butter with a lightsaber, doesn't it?

Building efficient and compatible selectors

Using exact value matches

Here's a trick: to get elements with exact data attribute value fights the accidental selection of partial matches:

$('[data-some="specificValue"]') // "This attribute goes to 11"

The importance of quotes

Always wrap the attribute value in quotes for compatibility:

$('[data-example="42"]') // "42 - Life, Universe, everything and data attribute value!"

The universal way

This method applies to any HTML tag with a data attribute, not only to a elements:

$('div[data-status="active"]') // Targets our beloved "active" divs from HTML cosmic zoo

jQuery's .data() vs .attr()

Reading attributes with .data()

When retrieving data attribute values, prefer .data() over .attr(). It keeps the type of the value:

var exampleData = $('a').data('example'); // "Can't touch this... .data()!"

Setting attributes with .attr()

To set a data attribute, use .attr():

$('element').attr('data-name', value); // "Bam! New attribute comin' through!"

Digging deeper into CSS selectors

Searching for partial matches

Find elements with a space-separated list in a data attribute:

$('[data-tags~="monday"]') // "Catchin' all the Monday feels"

###Data attribute starts with or ends with Capturing data attribute starting:

$('[data-filename^="report_"]') // "Because everyone loves a good REPORT first thing in the morning..."

Ending with:

$('[data-url$=".com"]') // "Welcome to the .com zone"

Non-jQuery selection

In a non-jQuery environment:

document.querySelectorAll('[data-customerID="22"]') // "Haha, I laugh in the face of jQuery! (Just kidding, jQuery, we still love you ❤)"

Evading the universal selector

Save performance by avoiding the universal selector *. Ensure that the tag is specified:

$('*[data-role="admin"]') // No! Bad developer! $('div[data-role="admin"]') // Good job, here's a cookie 🍪!

Tapping into data attributes in HTML

Here's how to define data attributes in HTML:

<a href="#" data-customerid="22">Link</a> <!-- CHALLAAAAANGE... ACCEPTED -->

Handling quotes omission

Omitting quotes only when data attribute value doesn't carry special characters:

$('[data-some=value]') // "Living life on the edge... of selector ambiguity"