How to store JavaScript object in HTML attribute?

HTML5 has a new attribute "data-*". The data-* attributes is used to store custom data to the page. By adding data-* attributes, even ordinary HTML elements can become rather complex and powerful program-objects.

Eg:
<div data-website-name="webspeckle.com"></div>
In the above example 'div' element has an attribute "data-website-name". This is a custom data attributes. The string "webspeckle.com" set to "data-website-name" attribute.

Set JSON string in 'data' attribute

<div data-website-name="webspeckle.com" data-website-data='{"name":"webspeckle.com","type":"blog"}'></div>
In the above example the JSON string '{"name":"webspeckle.com","type":"blog"}' set to the 'data-website-data' attribute.

Get the value of data attribute using JQuery
$("div").data("data-website-name") //webspeckle.com
$("div").data("data-website-data") //JSON Object
$("div").data("data-website-data").type //blog
Set value to data attribute using JQuery
<script>
var car =
{
color: "red",
        owner: "rahul"
}
$(document).ready(function()
{
      $("div").data("car",car)
});
</script>
Final code and demo is here

Demo

No comments:

Post a Comment