Explain Codes LogoExplain Codes Logo

Jquery selectors on custom data attributes using HTML5

javascript
prompt-engineering
selectors
custom-data-attributes
Anton ShumikhinbyAnton Shumikhin·Oct 29, 2024
TLDR

To quickly select HTML5 elements with specific data- attributes using jQuery, the attribute selectors are the key:

// Selects elements with 'data-role' attribute set to 'main' $('[data-role="main"]').action();

And for a partial match, let's say data-info starting with user_:

// Find pumpkin seeds in a watermelon, select data-info starting with 'user_' $('[data-info^="user_"]').action();

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:

// Excludes all elements that have 'data-status' set to 'archived', just like ignoring that stalker ex! $(':not([data-status="archived"])').action();

Filtering by text: The :contains selector

If you need to select elements containing a specific text, the :contains selector can help you out:

// Selects all 'p' elements containing the word 'JavaScript', because who doesn't like JS, right? $('p:contains("JavaScript")').action();

Embracing the power of attribute substring match

Use ^=, *=, $= to select elements with attributes starting with, containing, or ending with a given substring:

// Selects elements with 'data-type' attribute starting with 'image', time to find those memes! $('[data-type^="image"]').action(); // Selects elements with 'data-description' containing 'free', we all love freebies! $('[data-description*="free"]').action(); // Selects elements with 'data-file' ending with '.jpg'. You got yourself a bunch of photos. $('[data-file$=".jpg"]').action();

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:

// Stores 'data-role'='main' elements in a variable. Reuse responsibly 😉 var mainElements = $('[data-role="main"]');

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:

// Define data with .data() $('element').data('key', 'value'); // Now select with :data(), because jQuery UI is not just about widgets and effects! $(':data(key)').action();

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:

// Love the simplicity of Vanilla JS? This one's for you! document.querySelectorAll('[data-role="main"]').forEach(function(el){ // Do magic with each element });

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:

// The key to a successful day is coffee; likewise, the key to successful data attribute is .data() $('element').data('key', 'value');

Manual filtration using filter()

jQuery's filter() function provides a way to manually filter elements as per custom data:

// Only interested in elements that know the answer to universe's mysteries? filter() is your guy! $('elements').filter(function() { return $(this).data('key') === 'specificValue'; }).action();