0
0
HtmlHow-ToBeginner · 3 min read

How to Use Custom Data Attributes in HTML: Simple Guide

Use custom data attributes in HTML by adding attributes that start with data- followed by your chosen name, like data-user="123". These attributes store extra information on elements without affecting the page display and can be accessed easily with JavaScript.
📐

Syntax

Custom 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.

  • data-*: The prefix that tells the browser this is a custom data attribute.
  • name: Your chosen attribute name, like user-id or color.
  • value: The information you want to store, like 123 or blue.
html
<div data-user-id="123" data-color="blue">Content here</div>
Output
<div>Content here</div>
💻

Example

This example shows how to add custom data attributes to a button and then access them with JavaScript to show an alert with the stored data.

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Custom Data Attributes Example</title>
</head>
<body>
  <button id="infoBtn" data-user="Alice" data-age="30">Click me</button>

  <script>
    const button = document.getElementById('infoBtn');
    button.addEventListener('click', () => {
      const user = button.dataset.user;
      const age = button.dataset.age;
      alert(`User: ${user}, Age: ${age}`);
    });
  </script>
</body>
</html>
Output
A button labeled 'Click me' appears. When clicked, an alert shows: 'User: Alice, Age: 30'.
⚠️

Common Pitfalls

Common mistakes when using custom data attributes include:

  • Not prefixing attribute names with data-, which makes them invalid.
  • Using uppercase letters or spaces in attribute names, which is not allowed.
  • Trying to access data attributes in JavaScript without using the dataset property.

Always use lowercase and hyphens for names, and access them via element.dataset.name in JavaScript.

html
<!-- Wrong: missing data- prefix -->
<div user-id="123">Wrong</div>

<!-- Right: correct data attribute -->
<div data-user-id="123">Right</div>
Output
<div>Wrong</div> <div>Right</div>
📊

Quick Reference

PartDescriptionExample
data-Prefix for custom data attributesdata-
nameCustom attribute name (lowercase, hyphens allowed)user-id
valueValue stored as string"123"
Access in JSUse element.dataset.name (camelCase for hyphens)element.dataset.userId

Key Takeaways

Custom data attributes must start with 'data-' followed by a lowercase name.
Use hyphens in attribute names and access them in JavaScript with the dataset property.
They store extra info on HTML elements without affecting layout or style.
Avoid uppercase letters or missing 'data-' prefix to keep attributes valid.
JavaScript's dataset converts hyphenated names to camelCase for easy access.