0
0
HTMLmarkup~5 mins

Data attributes in HTML

Choose your learning style9 modes available
Introduction

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.

You want to add custom info to buttons to know what they do when clicked.
You need to store IDs or names on elements for JavaScript to use later.
You want to keep track of user choices or settings on parts of the page.
You want to add extra details to images or links without showing them.
You want to pass data from HTML to JavaScript easily.
Syntax
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.

Examples
A button with a data attribute named data-action holding the value "save".
HTML
<button data-action="save">Save</button>
A div storing a user ID as a data attribute.
HTML
<div data-user-id="12345">User Info</div>
An image with a data attribute describing the picture.
HTML
<img src="photo.jpg" data-description="A sunny beach">
Sample Program

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.

HTML
<!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>
OutputSuccess
Important Notes

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.

Summary

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.