Using HTML5 custom data attributes to store data on HTML elements

When writing JavaScripts for a web page, since the beginning of time, web developers have had the need to store extra data for HTML elements. I remember reading about custom data attributes in HTML5 some time ago, and recently Remy reminded me about them – they are here to save us!

Background

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 data-type and data-value:

	<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:

	<!DOCTYPE html>

Accessing custom data attributes via JavaScript

Then, naturally, you want to access them with JavaScript, and just do it like any other attribute:

	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!

Using dataset

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.

Demos

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>