Before, we used to either have invalid attributes with various values, extend/misuse existing attributes or just go crazy with class names containing data. But now with custom data attributes in HTML5, that is all history!
Using custom data attributes
It is actually as easy as it gets: make up any attribute name you want, such as “type”, “value” or similar, prepend “data-” to that value and you’re good to go! In this example we have made up two custom attributes for us named
<strong data-type="element" data-value="I am da law!"> Custom data attributes </strong>
This is completely valid HTML5 code, as long as you use the HTML5 doctype:
var type = document.getElementById("elm-name").getAttribute("data-type");
Pretty simple, right? And the best thing, this works in virtually all web browser known to man!
In the HTML5 specification, there is also a mention to use a certain
dataset property on elements and from there only read out custom data attribute values:
var type = document.getElementById("elm-name").dataset.type;
However, currently this is not implemented in any web browser.
A have put together a simple demo of using HTML5 custom data attributes as a part of my HTML5 – Information and samples for HTML5 and related APIs web site.