HTML5 data-* attribute
Weeks ago I was enjoying my free time playing around in twitter’s response html & ajax requests =D .. I have found a “data-*” attribute in the html metadata .. It reminded me with the old days when I used to write attributes from my own mind in ASP.NET Repeater to the repeated elements. just to use it later in Jquery click handler or something.. later on I found that this is just realted to HTML5’s dataset I read about years but actually I forgot it, horrible memory !
may be writing a couple of lines here won’t let me forget it again !=)
the good part is I started digging in W3C Draft to refresh my memory and know the changes dropped to it.
//so lets talk a little bit about it !
lets write some markup to play around with:
<div id="container"> <span data-color="black">Samsung 23' LCD</span> <span data-color="silver">BenQ 19' LCD</span> </div>
Now If you are familiar with simple DOM methods you will know that its simply possible to access these custom attributes with getAttribute() and change the values of it by setAttribute()
var target = document.getElementsByTagName("span"); alert(target.getAttribute("data-color")); //black target.setAttribute("data-color", "blue"); alert(target.getAttribute("data-color")); //blue
Till now we have nothing new, only a couple of “hand-made” attributes and normal getAttribute & setAttribute Methods..
its time now to look at HTML5 related API
HTML5 provide a new property called dataset that returns DOMStringMap (name-value pairs object)
See the highlighted lines:
var target = document.getElementsByTagName("span"); alert(target.getAttribute("data-color")); //black target.setAttribute("data-color", "blue"); alert(target.getAttribute("data-color")); //blue alert(target.dataset.color); // blue target.dataset.color = "red"; alert(target.dataset.color); // red
the dataset property gives you an access to the custom attributes you have made in the markup, the keys inside the dataset object doesn’t have “data-” part so “data-ballSize” would be “dataset.ballSize”.
Jquery data-* support:
We already know the .DATA() method in Jquery (added with V.1.2.3 -2008) .. a couple of months ago Jquery added support for HTML5’s dataset, lets see an example for that.
var target = $("span:first"); var myData = target.data; alert(myData.color); //black
myData will have All values of inserted in any data- attribute as JSON Object.
or you can directly get the values and use it. Like..
var target = $("span:first"); var myValue = target.data("color"); alert(myValue); //black
ThankQ for reading, Hope you enjoyed it.