Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

Discover how to focus on operators for Reactive Programming and how they are essential to react to data in your application.  Brought to you in partnership with Wakanda

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.





Learn how divergent branches can appear in your repository and how to better understand why they are called “branches".  Brought to you in partnership with Wakanda

Topics:

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

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}