Home  • Programming • JavaScript

HTML 5 data-* attributes, how to use them and why

It is always tempting to add custom attributes in HTML so that you can use the data stored there to do X. But if you do that there is no way of knowing if your HTML attribute will not be overridden in the future and used for something else and additionally you will not be writing valid HTML markup that can pass HTML 5 validator and with that you can create some very bad side effects. That is why there is a spec in HTML 5 called custom data attributes that enables number of useful features. You may go around and read the specs but the basic idea is very simple, you can add any attribute that starts with "data-" and that attribute will be treated as non-visible data for that attribute. By non-visible I mean that it is not something that gets rendered to the client so it does not affect the layout or style of the page but it is there in the HTML so in no way this is private. So let's get right into it, the following snippet is a valid HTML5 markup
  
<div id="awesome"  data-hash="3e4ae6c4e30e50e4fdfc7bf439a09974">Some awesome data</div>
Great so now how do you read the data from there? Well you can go through the elements and get the attributes you need or you can go and use jQuery if it is already there. Using jQuery's .data() API you can work with the "data-*" elements. One method is .data(obj) added in jQuery1.4.3 that basically retrieves data for the selected element. For example if you want to get the value of the data-hash attribute with the following snippet:
 var dataHashValue = jQuery("#awesome").data('hash');
 console.log(dataHashValue);
You can also use json syntax in the data fields for example if you have the following HTML:
<div id="awesome-json" data-awesome='{"game":"on"}'></div> 
Accessing data from js can be done directly just by adding the json key to the result :
  var gameStatus= jQuery("#awesome-json").data('awesome').game;
  console.log(gameStatus);
You can also set the data using .data(key,value) directly from JS. One important thing to remember is that the "data-*" attributes should be linked to the element in some way. They should add additional info about that element or the data it contains and not act just like storage for everything
In the JSON format we MUST use double-quoted strings.
The definition goes as this:
A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

Comments 0


Copyright © 2025. Powered by Intellect Software Ltd