JAVASCRIPT

Manipulate Custom Data Attributes on Elements

Learn to effectively read, write, and remove custom data attributes (`data-*`) on HTML elements using JavaScript, enabling dynamic data storage and interaction within the DOM.

// HTML Example: <div id="myElement" data-user-id="123" data-status="active"></div>

const myElement = document.getElementById('myElement');

// 1. Read a data attribute
const userId = myElement.dataset.userId; // '123'
const status = myElement.dataset.status; // 'active'
console.log(`User ID: ${userId}, Status: ${status}`);

// Note: data-user-id becomes dataset.userId (camelCase)
const rawUserId = myElement.getAttribute('data-user-id'); // '123'
console.log(`Raw User ID: ${rawUserId}`);

// 2. Set/Update a data attribute
myElement.dataset.status = 'inactive';
myElement.dataset.newSetting = 'value1';
console.log(`Updated Status: ${myElement.dataset.status}`);
console.log(`New Setting: ${myElement.dataset.newSetting}`);

// Using setAttribute for consistency or if you prefer
myElement.setAttribute('data-color', 'blue');
console.log(`Color: ${myElement.dataset.color}`);

// 3. Remove a data attribute
delete myElement.dataset.newSetting;
// Or using removeAttribute
myElement.removeAttribute('data-color');

console.log('After removal:', myElement.dataset.newSetting); // undefined
console.log('After removal:', myElement.dataset.color); // undefined

// You can also iterate through data attributes
console.log('All data attributes:');
for (const key in myElement.dataset) {
  console.log(`data-${key.replace(/([A-Z])/g, '-$1').toLowerCase()}: ${myElement.dataset[key]}`);
}
How it works: This snippet illustrates how to interact with custom `data-*` attributes using JavaScript. The `dataset` property of an HTML element provides a convenient way to access these attributes as an object, automatically converting kebab-case (e.g., `data-user-id`) to camelCase (e.g., `element.dataset.userId`). You can easily read, set, or update values by accessing properties of `dataset`. For removal, you can use `delete element.dataset.propertyName` or the more general `element.removeAttribute('data-attribute-name')`. This allows elements to store extra data without affecting their visual representation, useful for JavaScript logic.

Need help integrating this into your project?

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

Hire DigitalCodeLabs