What is Data Attribute in HTML: Simple Explanation and Examples
data attribute in HTML is a custom attribute that starts with data- and stores extra information on HTML elements. It allows developers to add private data that can be accessed by JavaScript or CSS without affecting the page layout or behavior.How It Works
Think of a data attribute as a small label you stick on an HTML element to hold extra information. This label doesn’t change how the element looks or behaves by itself, but it keeps useful data right inside the element.
For example, if you have a list of products on a page, you can add a data-price attribute to each product item to store its price. Later, JavaScript can read this price to calculate totals or show details without needing to change the HTML structure.
This works because any attribute that starts with data- is reserved for this purpose. Browsers ignore these attributes visually but keep them accessible for scripts and styles.
Example
This example shows a button with a data-user attribute storing a username. JavaScript reads this data and shows it in an alert when the button is clicked.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Data Attribute Example</title> </head> <body> <button id="greetBtn" data-user="Alice">Greet User</button> <script> const button = document.getElementById('greetBtn'); button.addEventListener('click', () => { const userName = button.dataset.user; alert('Hello, ' + userName + '!'); }); </script> </body> </html>
When to Use
Use data attributes when you want to store extra information on HTML elements that is not visible to users but useful for scripts or styling. This keeps your HTML clean and semantic without mixing data inside class names or IDs.
Common uses include:
- Storing IDs or keys for JavaScript to process
- Keeping configuration options for widgets
- Marking elements with state or category info
- Passing data to CSS for styling with attribute selectors
For example, an online store might use data attributes to hold product IDs or stock status, which JavaScript can then use to update the page dynamically.
Key Points
- Data attributes start with
data-and can have any name after the dash. - They store extra information without affecting page layout or behavior by default.
- JavaScript can easily access them via the
datasetproperty. - They help keep HTML semantic and clean by separating data from styling and structure.
- They are widely supported in all modern browsers.