15.4.3 Dataset Attributes

15.4.3 Dataset Attributes

It is sometimes useful to attach additional information to HTML elements, typically when JavaScript code will be selecting those elements and manipulating them in some way. Sometimes this can be done by adding special identifiers to the class attribute. Other times, for more complex data, client-side programmers resort to the use of nonstandard attributes. As noted above, you can use the getAttribute() and setAttribute() methods to read and write the values of nonstandard attributes. The price you pay, however, is that your document will not be valid HTML.

HTML5 provides a solution. In an HTML5 document, any attribute whose name is lowercase and begins with the prefix “data-” is considered valid. These “dataset attributes” will not affect the presentation of the elements on which they appear and they define a standard way to attach additional data without compromising document validity.

HTML5 also defines a dataset property on Element objects. This property refers to an object, which has properties that correspond to the data-attributes with their prefix removed. Thus dataset.x would hold the value of the data-x attribute. Hyphenated attributes map to camel-case property names: the attribute data-jquery-test becomes the property dataset.jqueryTest.

As a more concrete example, suppose that a document contains the following markup:

1 1 1 2 2 3 4 5 5 4 3 5 6 7 7 4 2 1

A sparkline is a small graphic—often a line plot—designed to be displayed within the flow of text. In order to generate a sparkline, you might extract the value of the dataset attributes above with code like this:

At the time of this writing, the datasetproperty is not implemented in current browsers, and the code above would have to be written like this:

var sparklines = document.getElementsByClassName("sparkline");

for(var i = 0; i < sparklines.length; i++) {

var elt = sparklines[i];

var ymin = parseFloat(elt.getAttribute("data-ymin"));

var ymin = parseFloat(elt.getAttribute("data-ymax"));

var points = elt.getAttribute("data-points");

var data = elt.textContent.split(" ").map(parseFloat);

drawSparkline(elt, ymin, ymax, data); // Not yet implemented

}

Note that the dataset property is (or will be, when implemented) a live, two-way interface to the data-attributes of an element. Setting or deleting a property of dataset sets or removes the corresponding data-attribute of the element.