Over a million developers have joined DZone.

Using HTML5 custom data attributes to store data on HTML elements

DZone's Guide to

Using HTML5 custom data attributes to store data on HTML elements

· Web Dev Zone ·
Free Resource

Access over 20 APIs and mobile SDKs, up to 250k transactions free with no credit card required

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!


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

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.


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.

#1 for location developers in quality, price and choice, switch to HERE.


Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}