HTML Custom Data Attributes
Why
The data-* attributes allows us to store extra information on an HTML element without having to use a non-semantic element or pollute the class name. They can contain information that is constantly changing, like a score in a game. It’s not a good idea to put content that is visible and accessible.
Reference: Using data-* attributes in JavaScript and CSS - Mozilla Hacks - the Web developer blog
What
data-*
attributes are global attributes. *
may be replaced by any lowercased alphabet characters (except xml
) and -
. The attribute value must be type of String
.
How
Developers can access an element’s custom data attributes via:
For Javascript, through HTMLElement’ dataset property, which is a DOMStringMap with an entry for each data-*
attribute. To get a custom data attribute, convert the part of the attribute name after data-
.
For CSS, use attr() function to retrieve the attribute value. Or attribute selectors to changes styles according to the value.
Where
Add custom data attributes to HTML
elements directly.
When
Before accessing custom data attributes, you need to retrieve the element first.