Jquery selectors on custom data attributes using HTML5
To quickly select HTML5 elements with specific data-
attributes using jQuery, the attribute selectors are the key:
And for a partial match, let's say data-info
starting with user_
:
In essence, just focus on the specific data attribute and value or pattern.
Excluding specific values
To search for elements excluding a particular value, use the :not
selector:
Filtering by text: The :contains selector
If you need to select elements containing a specific text, the :contains
selector can help you out:
Embracing the power of attribute substring match
Use ^=
, *=
, $=
to select elements with attributes starting with, containing, or ending with a given substring:
Improving performance with caching
Always cache selector references when you'll use them multiple times. It improves performance by avoiding constant querying of the DOM:
Dynamically accessing data with :data() of jQuery UI
On dynamic applications where data attributes might change at runtime, :data()
selector from jQuery UI comes handy:
Note: jQuery UI 1.7.0 or higher is needed for this.
No jQuery? No worries: Select in pure JavaScript
JavaScript's document.querySelectorAll
allows for selector choosing without jQuery:
Native methods are often faster than jQuery especially for complex queries. So sometimes, let's keep it simple.
A little performance side note
Running performance tests across various browsers can help you to choose the most efficient selection method. For example, Safari came first in a speed test comparison using PureJS.
Additional utility methods for custom data attributes
Set data attributes with .data()
With jQuery's .data("key", "value")
, you can set custom data attributes on elements:
Manual filtration using filter()
jQuery's filter()
function provides a way to manually filter elements as per custom data:
Was this article helpful?