HTML & CSS Interview Question #27

What are data-* attributes in HTML?

Forms, Validation, Metadata, Media, Responsive Images & Accessibility Junior Beginner

Quick Interview Answer

Custom data attributes let developers store application-specific data on HTML elements using names beginning with data-. JavaScript can access them through the element's dataset property.

Detailed Explanation

Custom data attributes let developers store application-specific data on HTML elements using names beginning with data-. JavaScript can access them through the element's dataset property.

They are useful for small pieces of metadata associated with an element, such as identifiers or UI configuration. They should not be used to expose secrets or replace a proper application state model for large or complex data.

Code Example

<button type="button"
        data-product-id="347"
        data-action="add-to-cart">
    Add to Cart
</button>

<script>
const button = document.querySelector("button");
console.log(button.dataset.productId); // "347"
</script>