Over a million developers have joined DZone.

Using HTML5 custom data attributes to store data on HTML elements

· Web Dev Zone

Start coding today to experience the powerful engine that drives data application’s development, brought to you in partnership with Qlik.

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.

Create data driven applications in Qlik’s free and easy to use coding environment, brought to you in partnership with Qlik.


Published at DZone with permission of Robert Nyman, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}