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 an HTML
attribute?
For example
<div data-x="A LARGE SET OF JSON DATA" id="x">
Or a large set of JSON data must be stored within <script>
tag, and an HTML
attribute is not a right place for a large set of data, even for data
attribute.
JSON can very easily be translated into JavaScript. JavaScript can be used to make HTML in your web pages.
HTML data-* AttributeThe data-* attribute gives us the ability to embed custom data attributes on all HTML elements. The stored (custom) data can then be used in the page's JavaScript to create a more engaging user experience (without any Ajax calls or server-side database queries).
JSON (JavaScript Object Notation, pronounced /ˈdʒeɪsən/; also /ˈdʒeɪˌsɒn/) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays (or other serializable values).
Adding a data attribute is easy. Any HTML element can have any number of data attributes added to its opening tag. We simply type data- followed by the name of our attribute into the element's opening tag alongside any other attributes we're already using.
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.
Say you want to save the object var dataObj = { foo: 'something', bar: 'something else' };
to an html data attribute.
Consider first stringifying the object such that we have var stringifiedDataObj = JSON.stringify(dataObj);
Then you can use jQuery to set the stringifiedDataObj as the data attribute e.g. with the jQuery.data()
API
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With