HTML5 data-* (custom data attribute)

Posted by Renso on Geeks with Blogs See other posts from Geeks with Blogs or by Renso
Published on Thu, 17 Nov 2011 12:43:00 GMT Indexed on 2011/11/17 17:52 UTC
Read the original article Hit count: 300

Filed under:

Goal:

Store custom data with the data attribute on any DOM element and retrieve it. Previously under HTML4 we used to use classes to store custom data, something to the affect of <input class="account void limit-5000 over-4999" /> and then have to parse the data out of the class In a book published by Peter-Paul Koch in 2007, ppk on JavaScript, he explains why and how to use custom attributes to make data more accessible to JavaScript, using name-value pairs. Accessing a custom attribute account-limit=5000 is much easier and more intuitive than trying to parse it out of a class, Plus, what if the class name for example "color-5" has a representative class definition in a CSS stylesheet that hides it away or worse some JavaScript plugin that automatically adds 5000 to it, or something crazy like that, just because it is a valid class name. As you can see there are quite a few reasons why using classes is a bad design and why it was important to define custom data attributes in HTML5.

Syntax:

You define the data attribute by simply prefixing any data item you want to store with any HTML element with "data-". For example to store our customers account data with a hidden input element:

<input type="hidden" data-account="void" data-limit=5000 data-over=4999  />

How to access the data:

account  -     element.dataset.account

limit    -     element.dataset.limit

You can also access it by using the more traditional get/setAttribute method or if using jQuery $('#element').attr('data-account','void')

Browser support:

All except for IE. There is an IE hack around this at http://gist.github.com/362081.

Special Note:

Be AWARE, do not use upper-case when defining your data elements as it is all converted to lower-case when reading it, so:

data-myAccount="A1234"

will not be found when you read it with:

element.dataset.myAccount

Use only lowercase when reading so this will work:

element.dataset.myaccount

© Geeks with Blogs or respective owner