HTML data-* attributes
How it’s done with jQuery
The jQuery function $(selector).data(name)
is used to retrieve values from data-*
html attributes.
However, it not only returns the values, it also stores a requested value in an internal storage cache. Once read, a data-
attribute can be removed, the values still are accessible via consecutive calls to data()
.
Also $(selector).data()
automatically coverts the attribute value to JSON if applicable.
And - just for completeness - $(selector).data(name, value)
can also be called with two arguments to set data in the internal storage.
How it’s done with native JavaScript
The usual way to access data-*
attributes with vanilla JavaScript is by using an elements dataset property: document.querySelector(selector).dataset
.
The big difference to jQuery’s data()
is this: If the data attribute is removed, the value is no longer available on the elements dataset property.
If the data should still be accessible, we have to take care of storing it somewhere before the attribute is removed.
There are many ways to accomplish this, but one convenient option is to set a custom property on the DOM Element instance.
Reading values with data(key)
The data attribute
Let’s have a look at one example of reading values from a data-*
attribute in jQuery and in Alpine.js.
For both examples, assume we have this element:
jQuery
// read data-example, parse JSON and store
$('#my-id').data('example');
$('#my-id').removeAttr('data-example');
console.log($('#my-id').data('example')); // => {name: "Alice"}
Alpine.js
const element = document.getElementById('my-id');
// omitting try/catch for brevity of example
// read data-example, parse JSON and store
element.__example = JSON.parse(element.dataset.example);
element.removeAttribute('data-example');
console.log(element.__example); // => {name: "Alice"}
Writing values with data(key, value)
If the value is a string or number, it can be set on an elements dataset
property.
// set with jQuery:
$(element).data('myPrice', 12.99);
// set with vanilla JavaScript
element.dataset.myPrice = 12.99;
However, it is not possible to set object references on an element dataset. With the jQuery data()
function any value can be set.
As a vanilla JavaScript alternative, consider setting the object reference using a custom property on the element itself. Choose a property name that is unlikely to conflict with the native browser DOM API or other extensions.
const myPrice = {ele: document.getElementById('pricebox'), value: 12.99, currency: 'EUR'};
// set with jQuery:
$(element).data('my-price', myPrice);
// set with vanilla JavaScript
element.__myPrice = myPrice;
Reading the value while using the dataset value as the default is a bit awkward compared to the jQuery code.