All All - 6 months ago 23
HTML Question

Is it bad to add JSON on HTML data attribute?

Since HTML

data
attribute allows adding any custom data, I wonder if it is a good idea to include a set of
JSON
list as a
data
attribute? Then, the corresponding
JSON
can be easily accessed by
JavaScript
events with
getAttribute("data-x")
.

In fact, my question is that: Is it standard, efficient, and reasonable to add a large set of data to a
HTML
attribute?

For example

<div data-x="A LARGE SET OF JSON DATA" id="x">


Or large set of JSON data must be stored within
<script>
tag, and a
HTML
attribute is not a right place for large set of data, even for
data
attribute.

Answer

Instead of storing everything in the data attribute you could use an identifier to access the data.

So for example you could do this :

var myBigJsonObj = { 
                      data1 : { //lots of data}, 
                      data2 : { //lots of data}                   

                   };

and then you had some html like so :

<div data-dataId="data1" id="x">

You can use jquery to get the data now like so :

var dataId = $('#x').attr('data-dataId');

var myData = myBigJsonObj[dataId];

This is the best approach imho.

Comments