I am passing an array of data from a jQuery script to an html element and trying to extract the data out of the element for use in a regular javaScript script. In the console I see the data being passed. Using the querySelector I can get the whole construct, but I cannot get the array back out of the construct.
The data looks like this:
[{"zone":"alessandros_office","value":76},
{"zone":"it_closet","value":72},
{"zone":"kitchen","value":79},
{"zone":"main_conference_room","value":152},
{"zone":"neils_office","value":58},
{"zone":"training_room","value":29}]
This is the html element that receives the data:
<div id="bubbleData" data-type="text" data-visitors=""></div>
This is the jQuery function that passes the data to the div after an AJAX call to get it.
this.Update = function (data) {
if (_.isUndefined(data) || _.isNull(data)) {
data = {};
}
console.log('Bubble js data: ', data);
this.BubbleChart.Update(data);
//$('#bubbleData').attr('data-visitors', data);
};
In the javascript script I extract the data and display it in a console.log with this:
const bubble = document.querySelector('[data-visitors]');
var data = bubble.dataset;
console.log('Visitor Data: ', data);
And in the console I see this:
Visitor Data:
DOMStringMap {id: 'visit', visitors: ''}
id: "visit"
visitors: "[{"zone":"alessandros_office","value":76},{"zone":"it_closet","value":72},{"zone":"kitchen","value":79},{"zone":"main_conference_room","value":152},{"zone":"neils_office","value":58},{"zone":"training_room","value":29}]"
According to mdm web docs https://developer.mozilla.org/en-US/docs/Learn/HTML/Howto/Use_data_attributes, I should be able to access the ‘visitors’ data with ‘bubble.dataset.visitors’, but a console.log of that turns up empty. How do I extract the visitors data?
2
Answers
See the manual for
data
:You can’t use standard DOM APIs to read data stored using jQuery’s
data
. It stores it internally to jQuery, not in the DOM.I suspect that there is just a misunderstanding between JSON and a Javascript Object.
This code illustrates the differences.