Data attributes let you store extra information inside HTML elements without changing how they look. This helps you keep data connected to parts of your page.
Data attributes in HTML
<element data-key="value">Content</element>
Data attributes always start with data- followed by your custom name.
The value is always a string inside quotes.
data-action holding the value "save".<button data-action="save">Save</button>
<div data-user-id="12345">User Info</div>
<img src="photo.jpg" data-description="A sunny beach">
This page has three buttons. Each button has a data attribute data-action with a different value. When you click a button, a message shows which action you clicked, using the data attribute value.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Data Attributes Example</title> <style> button { font-size: 1.2rem; padding: 0.5rem 1rem; margin: 0.5rem; cursor: pointer; } </style> </head> <body> <button data-action="save">Save</button> <button data-action="delete">Delete</button> <button data-action="edit">Edit</button> <script> const buttons = document.querySelectorAll('button'); buttons.forEach(button => { button.addEventListener('click', () => { alert(`You clicked the ${button.dataset.action} button.`); }); }); </script> </body> </html>
You can access data attributes in JavaScript using element.dataset.key, where key is the part after data- converted to camelCase.
Data attribute names should be lowercase and use dashes for readability, like data-user-id.
Data attributes do not affect the page style or layout by themselves.
Data attributes store extra info inside HTML elements without changing their look.
They always start with data- and can be read easily with JavaScript.
Use them to keep data connected to page parts for scripts or styling.