HTML5 Data Attributes with jQuery

jQuery has been able to store and retrieve arbitrary in data attributes against Nodes for a while, but you can also store and retrieve strings in HTML elements. With this technique we can write data to the page from a dynamic source without adding too much cruft to the rest of the markup (say, hidden DIVs or a chunk of JSON written to the page) whilst keeping the values attached to the element it belongs to.

Here's an example with embedded clicktrackers used for reporting against hits on tabs

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html>
<head>
  <title>Click tracker test</title>
</head>

<body>
  <ul id="ct">
    <li data-clk="http://www.example.com/?c=1">Clicktracker 1</li>
    <li data-clk="http://www.example.com/?c=2">Clicktracker 2</li>
  </ul>

  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script>
    var $ = window.jQuery;
    $(document).ready(function() {
      var ct = $('#ct li');

      ct.each(function() {
        console.log($(this).data('clk'));
      });
    });
  </script>
</body>
</html>