Store JSON object in data attribute in HTML jQuery

Actually, your last example:

<div data-foobar="{"foo":"bar"}"></div>

seems to be working well (see http://jsfiddle.net/GlauberRocha/Q6kKU/).

The nice thing is that the string in the data- attribute is automatically converted to a JavaScript object. I don’t see any drawback in this approach, on the contrary! One attribute is sufficient to store a whole set of data, ready to use in JavaScript through object properties.

(Note: for the data- attributes to be automatically given the type Object rather than String, you must be careful to write valid JSON, in particular to enclose the key names in double quotes).

Leave a Comment