Skip to content

Instantly share code, notes, and snippets.

@kingluddite
Created May 11, 2024 11:27
Show Gist options
  • Save kingluddite/820a1fbdb7f919109164f2eb06d7c263 to your computer and use it in GitHub Desktop.
Save kingluddite/820a1fbdb7f919109164f2eb06d7c263 to your computer and use it in GitHub Desktop.

The HTML5 data-* attribute provides a way to store custom data directly within HTML elements. Before its introduction, developers often resorted to using non-standard attributes or JavaScript hacks to achieve similar functionality. Let's explore an example to illustrate the difference:

Before HTML5 data-* attribute: Suppose you have a list of products displayed on a web page, and you want to associate additional information, such as a product ID or category, with each product element. Before HTML5, developers might have used non-standard attributes like class or id to store this information:

<ul>
  <li class="product" data-product-id="123">Product A</li>
  <li class="product" data-product-id="456">Product B</li>
  <li class="product" data-product-id="789">Product C</li>
</ul>

Then, in JavaScript, developers would have to parse these non-standard attributes to retrieve the custom data:

var products = document.querySelectorAll('.product');
products.forEach(function(product) {
  var productId = product.getAttribute('data-product-id');
  console.log(productId); // Output: 123, 456, 789
});

With HTML5 data-* attribute: With the introduction of HTML5, developers can use the data-* attribute to achieve the same result more cleanly and semantically:

<ul>
  <li class="product" data-product-id="123">Product A</li>
  <li class="product" data-product-id="456">Product B</li>
  <li class="product" data-product-id="789">Product C</li>
</ul>

And accessing the custom data in JavaScript becomes simpler:

var products = document.querySelectorAll('.product');
products.forEach(function(product) {
  var productId = product.dataset.productId;
  console.log(productId); // Output: 123, 456, 789
});

Using the data-* attribute provides a standardized and more maintainable way to store custom data within HTML elements, making the code easier to understand and work with for developers. Additionally, it improves accessibility and compatibility with various web development tools and frameworks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment