12.2 Defining Custom Attributes with “data-*” 275
var mmm = document.getElementsByClassName('red apple');
This helps us find all red fruit, all apples, and of course also a red apple.
12.2 Defining Custom Attributes with “data-*”
Previously, it was not possible in HTML to freely define custom attributes within
your application, but now the HTML specification offers a mechanism to achieve
exactly that: the data-* attribute. Its use could not be simpler and only requires
that the desired attribute has the prefix data-. There are few limitations for nam-
ing the attribute: It must be at least one character long and may not contain any
uppercase letters. Using the data entry of one of the 27 capital cities of our game
as an example, the data attributes for number of inhabitants, geographical loca-
tion, and associated country could look like this:
<li id=at class=q
data-pop=1705080
data-geo-lat=48.20833
data-geo-lng=16.373064
data-country='Austria'>Vienna
So how can you access your custom attributes? One option would be the classi-
cal method with getAttribute() and setAttribute(), but the specification has
something better to offer: the dataset property. It allows for retrieving and set-
ting all data attributes of an element via element.dataset:
var el = q.namedItem('at');
var pop = el.dataset.pop; // 1705080
var lat = el.dataset.geoLat; // 48.208
var lng = el.dataset.geoLng; // 16.373
var ctr = el.dataset.country; // Austria
// and two years later perhaps ...
el.dataset.pop = 1717034;
By the time you read the third line, which contains el.dataset.geoLat, it will
have become clear that hyphens have a special significance with data attributes;
why else would data-geo-lat suddenly turn into dataset.geoLat. Hyphens are
replaced by the next letter converted to uppercase—the special term for this way
of capitalizing is called CamelCase. Now you know why no uppercase letters are
allowed in data attributes: They could result in unexpected problems when re-
placing hyphens.
Unfortunately, support for element.dataset has not progressed well as yet. At the
time of this writing, only WebKit had implemented the dataset DOM property in
its Nightly builds. The game uses Remy Sharp’s html5-data.js as a workaround
for this shortcoming, a JavaScript shim that at least enables the reading of data
attributes. For setting, we must resort to the good old setAttribute() method.