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.

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

Set JSON string in 'data' attribute

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

Get the value of data attribute using JQuery
$("div").data("data-website-name") //
$("div").data("data-website-data") //JSON Object
$("div").data("data-website-data").type //blog
Set value to data attribute using JQuery
var car =
color: "red",
        owner: "rahul"
Final code and demo is here


No comments:

Post a Comment