HTML5 includes some great additions for authors wanting to work with microformats and microdata in markup. Last week I finished implementing the new
<data> elements in Firefox (see bugs 629801 and 839371). You can already use them in Nightly, and they should ship as part of Firefox 22. I wanted to say something about what they are, how you can use them, and why I implemented them.
The idea behind both elements is to make it easier for authors to include various kinds of data in markup. The
<data> element enables one to store extra machine-readable data along with textual content. For example, imagine I want to display a user's name, but also include their user ID without displaying it:
<data id="user" value="humphd">David Humphrey</data>
<data> element adds a new attribute,
value, which contains a string representation of your data. In script I can use the
.value property to get the reflected value:
var user = document.getElementById("user"), id = user.value;
In the past people used
data-* attributes to do something similar, for example:
<span id="user" data-username="humphd">David Humphrey</span>
This works well, but it introduces a non-standard way of naming such data. With the
<data> element, all such data is accessible via the
value attribute and property.
value of a
<data> element can be anything, from part numbers to IDs to co-ordinates--your scripts can parse it out and decide what to do with it. When the value you wish to store is really some form of date or time, the more appropriate choice is
<time> element a specialized form of
<data> used to add machine-readable dates and times to web pages. There are a few ways to use it:
<time>2013-03-05</time> <time datetime="2013-03-05">Today</time>
In both cases a
<time> element is used to markup a date. The latter uses the
.dateTime property (note the use of a capital 'T' on 'Time'). The
.dateTime property reflects the
I wanted to implement these for a few reasons. First, one of my classes is implementing the HTML5 <track> element right now, and I wanted to show them how Mozilla's new WebIDL bindings work with some simple examples. Second, I wanted to do some work on the ideas Atul mentioned in his blog post about Markup APIs.
It's neat to see that people are already using these elements in the wild. Github, for example, uses
<time> to record detailed info about commits, while not cluttering the UI with overly verbose data, for example:
<time class="<a>js-relative-date updated</a>" datetime="<a>2013-03-05T07:21:28-08:00</a>" title="<a>2013-03-05 07:21:28</a>">March 05, 2013</time>
I'm looking forward to seeing how people will use <data> as well--I haven't been able to track down any users of it yet, but I'm sure they're out there. If you know of any, throw links in the comments.
Go forth and microformat!