← Back to all snippets
JAVASCRIPT

Access and Manipulate HTML Data Attributes

Learn how to retrieve and update custom data attributes (e.g., `data-id`, `data-status`) on HTML elements using JavaScript's `dataset` property for storing element-specific information.

function manipulateDataAttributes(elementId, dataKey, newValue) {
    const element = document.getElementById(elementId);
    if (!element) {
        console.error(`Element with ID '${elementId}' not found.`);
        return;
    }

    // Get a data attribute
    const currentValue = element.dataset[dataKey];
    console.log(`Current value of data-${dataKey}:`, currentValue);

    // Set/Update a data attribute
    if (newValue !== undefined) {
        element.dataset[dataKey] = newValue;
        console.log(`Updated data-${dataKey} to:`, element.dataset[dataKey]);
    }

    // You can also remove a data attribute
    // delete element.dataset[dataKey];
    // console.log(`data-${dataKey} after deletion:`, element.dataset[dataKey]);

    return element.dataset; // Returns a DOMStringMap object of all data attributes
}

// Example Usage:
// <div id="productCard" data-product-id="12345" data-category="electronics" data-price="299.99">
//   Product Details
// </div>

const productData = manipulateDataAttributes('productCard', 'productId'); // Get data-product-id
console.log('All data attributes:', productData);

manipulateDataAttributes('productCard', 'category', 'home-appliances'); // Update data-category
manipulateDataAttributes('productCard', 'isOnSale', 'true'); // Add new data-attribute
How it works: This snippet demonstrates how to interact with HTML5 `data-*` attributes using the `dataset` property. It shows how to retrieve an attribute's value (e.g., `element.dataset.productId` for `data-product-id`), set or update its value, and implicitly, how to add new data attributes. The `dataset` property provides a convenient way to store and access custom data directly on DOM elements without relying on global variables or complex object structures.

Need help integrating this into your project?

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

Hire DigitalCodeLabs