JAVASCRIPT

Access and Modify Data Attributes on DOM Elements

Understand how to read and update custom `data-*` attributes on HTML elements using JavaScript. This facilitates data-driven DOM interactions and logic without modifying standard attributes.

const productCard = document.getElementById('productCard');
const updatePriceBtn = document.getElementById('updatePriceBtn');

if (productCard) {
    // Read data attributes
    const productId = productCard.dataset.productId;      // Accesses data-product-id
    const category = productCard.dataset.category;        // Accesses data-category
    let price = parseFloat(productCard.dataset.price);    // Accesses data-price

    console.log(`Product ID: ${productId}`);
    console.log(`Category: ${category}`);
    console.log(`Current Price: $${price}`);

    // Modify a data attribute
    productCard.dataset.price = (price * 0.9).toFixed(2); // 10% discount
    console.log(`New Price (after discount): $${productCard.dataset.price}`);

    // Add a new data attribute
    productCard.dataset.availability = 'in-stock';
    console.log(`Availability: ${productCard.dataset.availability}`);

    // Example: Update content based on data attribute
    const productNameElement = productCard.querySelector('h2');
    if (productNameElement) {
        productNameElement.textContent += ` (ID: ${productId})`;
    }
} else {
    console.error('Product card element not found!');
}

if (updatePriceBtn && productCard) {
    updatePriceBtn.addEventListener('click', () => {
        let currentPrice = parseFloat(productCard.dataset.price);
        productCard.dataset.price = (currentPrice + 10).toFixed(2);
        alert(`Price updated to: $${productCard.dataset.price}`);
    });
}
How it works: This snippet demonstrates how to interact with HTML5 `data-*` attributes using the `dataset` property in JavaScript. `dataset` provides a convenient way to read and write custom data associated with an element, converting `data-foo-bar` into `dataset.fooBar`. This is extremely useful for storing small pieces of application-specific data directly on elements, enabling data-driven UI logic and interactions without relying on global variables or complex DOM lookups.

Need help integrating this into your project?

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

Hire DigitalCodeLabs