We can’t change history, but we can change the future.
Be nice to each other.
@robertnyman

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:

Honored to have you comment here!
I agree that there’s certainly a risk for things like this getting abused (but the same goes for a number of things in HTML5, especially the loose HTML syntax demands).

But, and I know it sounds like a cliché, just because you can do bad doesn’t mean you have to.

I like to have it there in the toolbox for cases where it will really help, but will refrain from it as long as possible.

I think you forgot one important topic. WHY should anyone "store" (i mean not store as in permanent store but I don't know any better word) in the DOM? Specially now when we have local storage in html5?

What to me is extremely useful is that I can an attribute with any name, e.g. data-awesome, and have data in it and that all of this is valid HTML!

In the future, there is bound to be iteration possibilities and methods with the upcoming dataset.

mdmadph,

Go ahead then!

Andreas,

I think that is quite easy: people have done this for 10 years now, extending elements, saving intermediate values etc etc. For instance, the Dojo library has some features dependent on custom (and invalid) attributes.

Sure, localStorage and similar is great, but this is for other operations where you might need to extend the HTML directly and other cases.

I can't actually think of many legitimate uses for custom attributes. I just seems to me that they will get abused by developers adding very situation specific and unsemantic markup just to prop up there scripts when really in most situations there's a better way to approach the problem. Initially I liked the idea for adding microformat style data to documents but it appears that there's a microdata spec that covers that. Ranted about data attributes here.