0
0
HtmlHow-ToBeginner · 3 min read

How to Use Data Attributes in HTML: Simple Guide

Use data-* attributes in HTML to store custom data on any element. The syntax is data- followed by your name, like data-user="123". You can access these values in JavaScript using element.dataset.
📐

Syntax

Data attributes start with data- followed by a name you choose. The name must be lowercase and can include hyphens. The value can be any string.

Example parts:

  • data-: prefix to mark it as a data attribute
  • user-id: custom name chosen by you
  • "123": value stored as a string
html
<div data-user-id="123" data-role="admin">User Info</div>
Output
User Info
💻

Example

This example shows how to add data attributes to a button and read them with JavaScript to show an alert.

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>
</head>
<body>
  <button id="btn" data-product-id="456" data-product-name="Shoes">Buy Now</button>

  <script>
    const button = document.getElementById('btn');
    button.addEventListener('click', () => {
      const productId = button.dataset.productId;
      const productName = button.dataset.productName;
      alert(`Product: ${productName} (ID: ${productId})`);
    });
  </script>
</body>
</html>
Output
A button labeled 'Buy Now'. When clicked, an alert shows: "Product: Shoes (ID: 456)".
⚠️

Common Pitfalls

Common mistakes include:

  • Using uppercase letters in attribute names (should be lowercase).
  • Trying to access data attributes with getAttribute but forgetting to use dataset for easier access.
  • Using invalid characters or spaces in attribute names.

Correct usage ensures smooth access and avoids bugs.

html
<!-- Wrong: uppercase letters and spaces -->
<div data-user-id="789">Wrong</div>

<!-- Right: lowercase and hyphens -->
<div data-user-id="789">Right</div>
Output
Right
📊

Quick Reference

FeatureDescriptionExample
Attribute prefixAlways starts with 'data-'data-info="value"
Name rulesLowercase letters, digits, hyphens onlydata-user-id
Value typeAny stringdata-count="10"
Access in JSUse element.dataset.nameelement.dataset.userId
Invalid namesNo spaces or uppercase lettersdata-User Id (wrong)

Key Takeaways

Use data attributes with the prefix 'data-' followed by lowercase names to store custom data.
Access data attributes easily in JavaScript using the 'dataset' property.
Avoid uppercase letters and spaces in data attribute names to prevent errors.
Data attribute values are always strings but can represent any data you need.
Data attributes help keep HTML semantic while storing extra info for scripts.