MyInternships.in

HTML5

What are Custom Attributes in HTML5?

HTML5 introduced custom data attributes, written as data-*, that let you attach arbitrary private data to any HTML element without breaking validation. You choose the name after data-, store a value, and read it back easily in JavaScript through the element's dataset property.


What Are data-* Attributes?

A custom attribute is any attribute whose name starts with data- followed by at least one lowercase character, for example data-user-id or data-price. They are valid HTML5, do not affect rendering, and are meant to hold custom data for scripts to use.

The Naming Rule and dataset Mapping

HTML attributeJavaScript dataset property
data-idelement.dataset.id
data-user-nameelement.dataset.userName
data-max-countelement.dataset.maxCount
ℹ️

Hyphenated names become camelCase in dataset: data-user-name is read as dataset.userName. Values are always strings, so convert with Number() or JSON.parse() when needed.

Runnable Interactive Example

Reading data-* values with dataset on click
Example
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Custom Data Attributes</title>
</head>
<body>
  <h2>Product List</h2>
  <button data-id="101" data-price="499" onclick="show(this)">Pen Drive</button>
  <button data-id="102" data-price="1299" onclick="show(this)">Keyboard</button>

  <p id="out">Click a product to see its data.</p>

  <script>
    function show(btn) {
      var id = btn.dataset.id;
      var price = Number(btn.dataset.price);
      document.getElementById("out").textContent =
        "Product ID " + id + " costs Rs. " + price;
    }
  </script>
</body>
</html>

Common Uses

  • Storing an item id or price for JavaScript event handlers.
  • Passing configuration to a widget without extra markup.
  • Filtering or sorting lists based on data-category values.
  • Holding state for CSS attribute selectors like [data-active].
⚠️

data-* attributes are for private data used by YOUR scripts. Do not store sensitive information in them — they are visible in page source.

Key Takeaways

  • Custom attributes use the data-* prefix and are valid HTML5.
  • Read them in JavaScript via element.dataset (camelCased).
  • Values are always strings — convert types as needed.
  • Great for attaching per-element data to scripts and CSS.

Related HTML Topics

Keep learning with these closely related tutorials.

Ready to use your HTML skills?

Find web development internships and fresher jobs across India.

Browse Web Dev Internships