HTML5 custom attributes - Why would I use them?

Kriem picture Kriem · Feb 17, 2011 · Viewed 11.7k times · Source

I can't seem to understand why I should be happy with HTML5 allowing custom attributes? Why would I use them?

Answer

zzzzBov picture zzzzBov · Feb 17, 2011

I assume you're referencing the HTML5 [data-*] attributes.

The advantage is that you can easily associate some scripting data (still semantic, but not for display) with your elements without having to insert inline javascript all over the place, and it will be valid HTML5. To do the same thing in HTML4 would require specifying a custom namespace, and add some namespaced attributes.

Say you've got a list of items for sale, you may want to store the numeric price without trying to parse a string:

<ul>
  <li data-price="5">Item 1 is only $5 this week!</li>
  <li data-price="1">Sale on Item 2, only $1</li>
  ...
</ul>

If you allow your user to mark a number of different items to buy, you can easily pull out the numeric value to display a running total.

Alternatively, you could have put the numbers in a span with a specific class, find the right span on the right item, and pull out the value that way, but [data-*] attributes reduce the amount of markup/script necessary to do the same thing.

If you don't want to use it, you don't need to. There are many ways of associating data with elements, this is just a new one.

Additionally, the new dataset JavaScript API provides a consistent means of declaratively accessing the values stored in [data-*] attributes.

For jQuery users, .data() and .attr() can be used to access [data-*] attributes, and I have written up a detailed answer on when you would want to use one over the other.