What is data attribute in HTML and how to use it?

← PrevNext →

The data-* attribute allow developers to add some extra information to an element on a web page (or an application), which can later be used for processing. The data will remain hidden from the user. However, the developer can use the data as and when required.

What is data attribute?

Any element whose attribute has a prefix (or starts with) a data-, is a data attribute. For example, I have few <div> elements and I'll add some extra information to each element, using the "data attribute".

<div class="emp" data-name="arun" data-empcode="cd001">
    some text here... 
</div>
<div class="emp" data-name="mark" data-empcode="cd0014">
    some text here... 
</div>
<div class="emp" data-name="charlie" data-empcode="cd003">
    some text here... 
</div>
Try it

In the above example, I have defined two data attributes namely, "data-name" and "data-empcode" to each DIV element. So now, each element has a unique set to "data attributes".

You may also like this... How to get data attribute of a element dynamically and use the data to fetch more data from a remote JSON file?

👉 These extra information attached to an element will remain hidden, that is, it will not be displayed anywhere on the web page.

👉 The "data-*" attribute should have at-least one character, immediately after the "hyphen".

👉 The "data-*" attribute can hold any kind of value (numbers, decimal values, alphabets, special characters etc.) inside the double quotes.

👉 It can be used with any HTML element.

👉 The "data-*" attribute can be accessed using JavaScript. See this example.

How useful it is in actual scenarios? I think you should see this.

← PreviousNext →