Share
What are data- attributes good for?
Question
Hi,
I’d like to know What are data- attributes good for? And how they are used?
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Answer ( 1 )
In HTML, data attributes are used to store custom data private to the page or application. They are defined by the data-* attribute, where * represents a placeholder for the name of the data attribute. The values of data attributes are strings, and are typically used to store data that is not meant to be displayed to the user or interpreted as part of the content of the page, but rather is meant to be used in the background by scripts.
In JavaScript, you can access the values of data attributes using the getAttribute method. For example, given the following element:
You can access the values of the data attributes like this:
You can also use the dataset property of an element to access the values of data attributes. The dataset property is an object that contains a property for each data attribute of the element. The names of the properties are the names of the data attributes, with the data- prefix removed.
For example, you can access the values of the data attributes in the previous example like this:
Note that the dataset property is only supported in modern browsers, so if you need to support older browsers, you should use the getAttribute method instead.