Explain Codes LogoExplain Codes Logo

Get list of data-* attributes using JavaScript / jQuery

javascript
data-attributes
performance
jquery
Alex KataevbyAlex Kataev·Aug 13, 2024
TLDR

To obtain all data-* attributes from an HTML element using javascript, iterate over element.attributes, and gather the attributes that match the data- pattern:

const dataAttrs = [...document.getElementById('elementId').attributes] .filter(attr => attr.name.startsWith('data-')) // "data-" goes brrr .reduce((obj, attr) => { obj[attr.name] = attr.value; return obj; }, {});

With jQuery, you can use the .data() method, which grabs all data-* attributes in an instant:

const dataAttrs = $('#elementId').data(); // One line to rule them all

Both these snippets result in an object with data- attributes as keys and their corresponding values as object values - ideal for quick usage or further data manipulation.

Surpassing theory: dive into practice with data attributes

Data attributes, primarily used to store extra information, can be attached to standard HTML elements, completely eliminating the need for extra JavaScript or jQuery storage solutions. An interesting point to remember is that JavaScript will automatically convert the attribute values to a suitable type (numeric string to number, for example) during retrieval.

Master-level data attribute manipulation

CamelCase conversion: ride the hump

In modern browsers using element.dataset, data attribute names are automatically presented in camelCase format, turning a data-my-attribute into element.dataset.myAttribute.

Regular Expressions: the unsung heroes

For older browsers that might not support .dataset, parsing data-* attributes using regular expressions can save the day:

const el = document.getElementById('elementId'); const dataAttrs = {}; for (let i = 0; i < el.attributes.length; i++) { // Let's take a field trip through the attributes const attrName = el.attributes[i].name; if (/^data-/.test(attrName)) { // if it looks like a duck, swims like a duck... const key = attrName.substring(5).replace(/-([a-z])/g, g => g[1].toUpperCase()); // to camelCase or not to camelCase dataAttrs[key] = el.getAttribute(attrName); } }

jQuery's secret power: internal caching

When dealing with jQuery and the .data() method, the initial access pulls in of data attributes into an internal store for efficiency. This store is used for all subsequent access, not the DOM.

Extra knowledge: edge cases and performance tips

Edge cases: don't get cornered

While using data-* attributes is often smooth sailing, there are specific situations where you must tread with caution. For instance, the synchronization of data values. If you alter a data-* attribute directly using .attr() after accessing it with .data(), the internal jQuery cache will not update. In such cases, use .attr() for changes to reflect.

Performance matters: dealing with data feasts

When working with large sets of elements or data-* attributes, performance can take a hit. Instead of calling .data() individually for each attribute, prefer a single call to fetch all data attributes:

// Faster const allData = $('#elementId').data(); // Slower const role = $('#elementId').data('role'); const info = $('#elementId').data('info');

This way, the internal cache functionality of jQuery is leveraged to its maximum, reducing the number of times data needs to be fetched directly from the DOM.