Introduction to data-* Attributes in HTML

html data attributes tutorial
10 November 2024

What are the uses of data-* attributes in HTML?

Data-* attributes are one of the lesser-known capabilities in HTML that are used to store custom data in HTML elements. If you're a developer who prefers HTML to be clean and understandable, there’s no need to add unnecessary values to classes and IDs, data-* comes in handy.

Data-* attributes have existed since HTML5 and allow you to add information to elements that can be accessed via CSS or JavaScript. In other words, you can add extra information that needs to be processed by the HTML elements themselves without disrupting the structure of the HTML presentation.

Using this feature is very simple. Just prefix your desired name with data-, like data-user-id or data-product-name. These values will not display directly in the browser’s inspector, but can be accessed from JavaScript for dealing with this data; something that is quite useful when you have extra data that you need but don't want them to appear in the HTML view.

Another point is that data-* is only for storing simple data and should not be used for large or complex data; meaning that it is more suitable for cases where the data is small and temporary, like functionalities that you want to trigger on click or other user interaction events.

How to add a data-* attribute to an element?

<div class="product" data-product-id="123" data-product-type="electronics">
<h2>Product: Television</h2>
</div>

Here, we have a <div> that contains two data-* attributes: data-product-id and data-product-type used to identify the product and type of product respectively.


- <div class="product" data-product-id="123" data-product-type="electronics"> : This creates a div with the class "product" and adds two data attributes, one for identifying the product and the other for its type.


- <h2>Product: Television</h2> : This is a title that displays the name of the product. This information is part of the div content.


- </div> : This marks the end of the div element.

FAQ

?

Why do we use data-* attributes?

?

Does using data-* affect SEO?

?

How can I access data-* with JavaScript?