HTML5 Data attributes in HTML and jQuery

When writing javascript, it is often necessary to include metadata in the HTML markup, to help define some element or behaviour. There are common options available. You can use hidden inputs and/or standard attributes like class or title to store this metadata. However with HTML5’s data attribute, storing and parsing this data has become a whole lot easier and cleaner.

The syntax is straightforward. Any attribute prefixed with data- will be treated as data storage.

<div class="test" data-foo="bar"></div>

jQuery accesses this data like so…

var data = $( 'div.test' ).data( 'foo' ); // returns bar

Support for the data attribute has been added since jQuery version 1.4.3. jQuery’s implementation is smart enough that it can parse the attribute easily and even determine the correct data type used.

What I have found really useful is the fact that the jQuery can parse JSON syntax and return a JSON object. This makes passing data in PHP trivial, using the json_encode method. We also need to use htmlspecialchars method to escape or convert any quotes in the JSON string.