How can custom data attributes be used in JavaScript, and what are their benefits?
Instruction: Discuss the purpose of custom data attributes in HTML and how they can be interacted with in JavaScript.
Updated
Official answer available
Read the opening below, then unlock the full answer and practical guidance.
Custom data-* attributes attach application-specific string data to HTML elements. HTMLElement.dataset maps dash-separated names to camelCase property names, so data-user-id becomes dataset.userId.
const button = document.createElement('button'); button.type = 'button'; button.textContent = 'View profile'; button.dataset.userId = '12345'; console.log(button.getAttribute('data-user-id')); // 12345 button.dataset.count = 0; console.log(button.dataset.count === '0'); // true button.dataset.enabled = false; console.log(button.dataset.enabled); // 'false', still a nonempty string console.log(Object.hasOwn(button.dataset, 'userId')); // true...