How do we embed custom data attributes on all HTML elements?

Custom data attributes in HTML allow you to embed custom data private to your webpage or application. The data-* attribute adds custom values to any HTML element without interfering with the standard HTML structure or validation.

Data attributes are commonly used to store extra information that can be accessed later via JavaScript for enhanced user interactions, configurations, or metadata storage.

Syntax

Following is the syntax for using custom data attributes −

<tag data-attribute-name="value">Content</tag>

The data-* attribute consists of two parts −

  • Attribute name − Must start with "data-" followed by at least one character. The name should contain only lowercase letters, numbers, hyphens (-), periods (.), colons (:), and underscores (_).

  • Attribute value − Can be any string value that contains the custom data you want to store.

Data Attribute Structure data-product-id="12345" Required prefix Custom name Custom value

Accessing Data Attributes with JavaScript

JavaScript provides two ways to access data attributes −

  • getAttribute() methodelement.getAttribute("data-attribute-name")

  • dataset propertyelement.dataset.attributeName (converts kebab-case to camelCase)

Using Data Attributes for Product Information

Following example shows how to embed custom data attributes in a product list −

<!DOCTYPE html>
<html>
<head>
   <title>Custom Data Attributes - Products</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Product List</h2>
   <ul style="list-style: none; padding: 0;">
      <li data-id="1" data-price="INR 1899" data-category="clothing" style="padding: 10px; border: 1px solid #ddd; margin: 5px 0;">Shirt</li>
      <li data-id="2" data-price="INR 2799" data-category="clothing" style="padding: 10px; border: 1px solid #ddd; margin: 5px 0;">Pant</li>
      <li data-id="3" data-price="INR 4599" data-category="outerwear" style="padding: 10px; border: 1px solid #ddd; margin: 5px 0;">Jacket</li>
   </ul>
   <p><em>Note: The data attributes (id, price, category) are embedded in each list item but not visible to users.</em></p>
</body>
</html>

The output shows a simple product list. The custom data attributes are embedded in the HTML but not visible to users −

Product List

Shirt
Pant  
Jacket

Note: The data attributes (id, price, category) are embedded in each list item but not visible to users.

Interactive Data Attributes with JavaScript

Following example demonstrates how to access and display custom data attributes using JavaScript −

<!DOCTYPE html>
<html>
<head>
   <title>Interactive Data Attributes</title>
   <style>
      .player-cell {
         padding: 10px;
         border: 1px solid #ccc;
         cursor: pointer;
         text-align: center;
         background-color: #f9f9f9;
      }
      .player-cell:hover {
         background-color: #e9e9e9;
      }
      table {
         border-collapse: collapse;
         margin: 20px 0;
      }
   </style>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <h2>Cricket Players</h2>
   <p>Click on a player to see their team information:</p>
   
   <table>
      <caption style="font-weight: bold; margin-bottom: 10px;">International Players</caption>
      <tr>
         <td class="player-cell" onclick="showPlayerInfo(this)" data-player-team="Afghanistan" data-player-role="Bowler">Rashid Khan</td>
         <td class="player-cell" onclick="showPlayerInfo(this)" data-player-team="Pakistan" data-player-role="Batsman">Babar Azam</td>
      </tr>
      <tr>
         <td class="player-cell" onclick="showPlayerInfo(this)" data-player-team="England" data-player-role="Wicket Keeper">Jos Buttler</td>
         <td class="player-cell" onclick="showPlayerInfo(this)" data-player-team="Australia" data-player-role="Batsman">Steve Smith</td>
      </tr>
      <tr>
         <td class="player-cell" onclick="showPlayerInfo(this)" data-player-team="India" data-player-role="Bowler">Jasprit Bumrah</td>
         <td class="player-cell" onclick="showPlayerInfo(this)" data-player-team="West Indies" data-player-role="All Rounder">Jason Holder</td>
      </tr>
   </table>
   
   <div id="player-info" style="margin-top: 20px; padding: 10px; background-color: #e8f4fd; border-radius: 5px; display: none;"></div>
   
   <script>
      function showPlayerInfo(element) {
         var playerName = element.textContent;
         var team = element.getAttribute("data-player-team");
         var role = element.getAttribute("data-player-role");
         
         var infoDiv = document.getElementById("player-info");
         infoDiv.innerHTML = "<strong>" + playerName + "</strong> is a " + role + " from " + team + ".";
         infoDiv.style.display = "block";
      }
   </script>
</body>
</html>

When you click on any player name, the JavaScript function extracts the custom data attributes and displays the player's team and role information below the table.

Using Dataset Property

The modern approach to access data attributes is through the dataset property, which automatically converts kebab-case attribute names to camelCase −

<!DOCTYPE html>
<html>
<head>
   <title>Dataset Property Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
   <div id="product" data-product-id="12345" data-product-name="Laptop" data-product-price="50000">
      Product Information
   </div>
   
   <button onclick="showProductData()">Show Product Data</button>
   <div id="output" style="margin-top: 15px; padding: 10px; background-color: #f8f9fa;"></div>
   
   <script>
      function showProductData() {
         var product = document.getElementById("product");
         var output = document.getElementById("output");
         
         // Using dataset property (modern approach)
         var productId = product.dataset.productId;
         var productName = product.dataset.productName;
         var productPrice = product.dataset.productPrice;
         
         output.innerHTML = "<strong>Product Details:</strong><br>" +
                           "ID: " + productId + "<br>" +
                           "Name: " + productName + "<br>" +
                           "Price: ?" + productPrice;
      }
   </script>
</body>
</html>

The dataset property converts data-product-id to dataset.productId, making the code more readable and modern.

Data Attributes vs Other Approaches

Approach Pros Cons
Data Attributes HTML5 standard, accessible via CSS and JS, valid HTML String values only, visible in DOM
Hidden Input Fields Can store any data type Creates extra DOM elements, affects form submission
JavaScript Variables Any data type, not visible in DOM No HTML-element association, lost on page reload
CSS Classes Semantic meaning, styling integration Limited data storage, not meant for data

Common Use Cases

Data attributes are commonly used for −

  • Configuration data − Widget settings, API endpoints, or component options

  • Tracking information − Analytics data, user behavior tracking

  • State management − Element states in JavaScript applications

  • CSS styling − Conditional styling based on data attribute values

  • Form enhancement − Additional validation rules or processing information

Conclusion

Custom data attributes provide a clean, standards-compliant way to embed extra information in HTML elements. They enable rich JavaScript interactions while keeping your HTML semantic and valid. Use data attributes when you need to associate custom data with HTML elements for client-side processing or styling purposes.

Updated on: 2026-03-16T21:38:53+05:30

654 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements