How to find an element based on a data-attribute value in jQuery?
jQuery makes it easy to select elements based on custom data-
attributes, a feature widely used for storing small bits of extra information in HTML. Here’s how to target those elements quickly and cleanly.
1. The Attribute Selector
You can use jQuery’s attribute selector to find any element that has a particular data-attribute value:
$('[data-role="admin"]').css('color', 'red');
This snippet selects all elements where data-role="admin"
and applies a red text color.
2. Accessing the Data Value
Once you’ve selected an element, you can retrieve its data value using either:
.attr('data-attribute')
– Directly reads the HTML attribute..data('attribute')
– Uses jQuery’s data method (recommended when working heavily with data- attributes).
For example:
const role = $('[data-role="admin"]').data('role'); console.log(role); // "admin"
jQuery automatically maps data-*
attributes to .data()
keys.
3. Why Use Data-Attributes?
- Organization: Keep small bits of structured data in your markup without polluting the global namespace.
- Flexible UI Enhancements: Hide extra info in the element itself, making it straightforward to build dynamic UIs, tooltips, or interactive widgets.
- Easy to Read and Maintain: The
data-
prefix signals that the attribute is reserved for custom usage, improving code clarity.
4. Combining Multiple Data-Attributes
You can chain selectors if you need to match multiple data-attributes. For instance, to find elements that are both data-role="admin"
and data-active="true"
:
$('[data-role="admin"][data-active="true"]').hide();
Any element that meets both conditions is selected.
Take Your JavaScript Skills Further
To become truly proficient in front-end development—beyond jQuery—you need a solid grounding in JavaScript fundamentals. Consider exploring:
-
Grokking JavaScript Fundamentals
Ideal for mastering the essential concepts of the language, from closures and prototypes to promises and async/await. -
Grokking the Coding Interview: Patterns for Coding Questions
Perfect if you’re preparing for rigorous technical interviews, focusing on pattern-based solutions to common coding challenges.
And if you’d like hands-on practice under real interview conditions, check out the Coding Mock Interviews at DesignGurus.io. You’ll receive real-time feedback from ex-FAANG engineers, helping you refine both your technical and communication skills.
In summary, jQuery’s attribute selectors (e.g., [data-role="admin"]
) let you zero in on elements by their data-attributes. This approach keeps your code organized, maintainable, and flexible for building dynamic user interfaces.