Using HTML5’s Data Attributes With jQuery

While the HTML5 specification apparently won't be finalized until 2014, you can use one of its more useful new additions, the data attribute, right now with jQuery for easy access to extra data.

When you are creating a dynamic page, you often need to store some additional data on an html element that will be used later when interacting with the page. Right now, developers often use non-existent class names or the rel attribute as a solution, or they add their own attributes, which is not valid HTML.

For example:

<img src="picture.jpg" largeimage="picturelarge.jpg">

<li rel="menu1">Menu item</li>

Browsers just ignore attributes they don't support, so it has no negative effect. While this works, it is not the most elegant solution and is not valid HTML.

HTML5 introduces the data attribute to html elements. You can add multiple data attributes to an element. It works differently than other html attributes. The attribute begins with data, then has a dash and the name of the data item.


<img id="pic" src="picture.jpg" data-large="picturelarge.jpg"

data-productid="52" data-license="creative commons">

The img tag has three data attributes – large, productid and license. These can be accessed by getting the attribute, or by using the element's dataset object. Each data attribute becomes a named property of the dataset object:

Unfortunately, that method is not useable right now because of lack of browser support for the dataset object.
The solution is to use jQuery 1.43 or later, which has full support for the data attributes through the data() method. It does not rely on the dataset object, so it is compatible with non-HTML5 browsers.
Using the img example above, you can access the values of the data attributes like this:

$('#pic').data('productid') // 52

$('#pic').data('large') // picturelarge.jpg

While you could have just used the attr() to retrieve the value using the full attribute name ("data-productid"), the data() method is more elegant and readable, and has enhanced functionality. It can handle json encoded attributes, for example:

<li id='line1' data-options='{"color":"black","interior":"gray"}'>

Aston Martin</li>

The options attribute is automatically parsed by the data() method into named properties:

$('#line1').data("options").color //black

$('#line1').data("options").interior //gray

Data can also be added through code to an element with the data() method. It also has an event model that can be attached to for processing when data is read or set. For more info on data(), see the jQuery documentation on it.

jQuery provides an excellent way to start using HTML5 now without having to wait until browsers catch up.