JAVASCRIPT

Reading and Writing Data Attributes via Dataset

Discover how to easily read and write custom HTML data attributes in the DOM using JavaScript's built-in dataset property.

const card = document.querySelector('.user-card');

// Reading data-user-id="123" and data-role="admin"
const userId = card.dataset.userId;
const userRole = card.dataset.role;

// Writing a new data attribute
card.dataset.status = 'active';
How it works: The 'dataset' property provides a convenient API for accessing custom 'data-*' attributes on elements. Hyphenated attribute names like 'data-user-id' are automatically converted to camelCase ('dataset.userId') in JavaScript.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs