What are data attributes in HTML?
HTMLThe short answer
Data attributes are custom attributes you can add to any HTML element by prefixing them with data-. They let you store extra information on elements without using non-standard attributes or hidden elements. You can access them in JavaScript using the dataset property.
How they work
<button data-user-id="42" data-action="delete"> Delete User</button>In JavaScript:
const button = document.querySelector('button');// Access via dataset (camelCase)console.log(button.dataset.userId); // "42"console.log(button.dataset.action); // "delete"// Access via getAttributeconsole.log(button.getAttribute('data-user-id')); // "42"The naming convention is: data-user-id in HTML becomes dataset.userId in JavaScript. Hyphens are converted to camelCase.
Common use cases
Storing IDs for event handlers:
<ul> <li data-id="1">Apple</li> <li data-id="2">Banana</li> <li data-id="3">Cherry</li></ul>document .querySelector('ul') .addEventListener('click', (e) => { const id = e.target.dataset.id; if (id) { console.log(`Clicked item ${id}`); } });Configuring JavaScript behavior:
<div data-carousel data-autoplay="true" data-interval="3000"> <!-- carousel content --></div>Styling with CSS:
[data-status='active'] { color: green;}[data-status='inactive'] { color: gray;}In React
In React, data attributes work just like any other HTML attribute:
<button data-testid="submit-btn" data-user-id={userId}> Submit</button>They are commonly used with testing libraries like React Testing Library:
screen.getByTestId('submit-btn');Interview Tip
Keep the answer simple — data attributes store custom data on HTML elements using the data- prefix, accessed via dataset in JavaScript. The most practical example is event delegation, where you store IDs on list items and read them in a parent event handler. Mentioning the testing library use case shows real-world experience.
Why interviewers ask this
This tests your HTML knowledge and how well you understand the DOM API. Data attributes are used in real applications for event handling, testing, and configuring JavaScript behavior. Knowing how they work shows you understand the building blocks of the web platform.