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
$(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.
The usual way to access
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:
Writing values with data(key, value)
If the value is a string or number, it can be set on an elements
However, it is not possible to set object references on an element dataset. With the jQuery
data() function any value can be set.
Reading the value while using the dataset value as the default is a bit awkward compared to the jQuery code.