Selecting element by data attribute with jQuery
To select elements by data attribute in jQuery, use:
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"
:
And your element is good to go for any jQuery action, like adding a class:
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:
The importance of quotes
Always wrap the attribute value in quotes for compatibility:
The universal way
This method applies to any HTML tag with a data attribute, not only to a
elements:
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:
Setting attributes with .attr()
To set a data attribute, use .attr()
:
Digging deeper into CSS selectors
Searching for partial matches
Find elements with a space-separated list in a data attribute:
###Data attribute starts with or ends with Capturing data attribute starting:
Ending with:
Non-jQuery selection
In a non-jQuery environment:
Evading the universal selector
Save performance by avoiding the universal selector *
. Ensure that the tag is specified:
Tapping into data attributes in HTML
Here's how to define data attributes in HTML:
Handling quotes omission
Omitting quotes only when data attribute value doesn't carry special characters:
Was this article helpful?