I'm sure this is answered somewhere, but it is my lack of terminology knowledge that can't find where to look.
I am dynamically creating some Html as a result of some json data loaded from the server.
I am using createElement, and setAttribute to create the html and append it to the main body.
However, my dynamic html contains a "data-" attribute, which has further nested properties. An example end goal is such:
<li>
<span class=item data-item='{"width": 100, "height": 100,
"properties": { "Name": "foo", "Surname": "bar" }}'></span>
</li>
I have had some success when running:
li.setAttribute("data-item", '{"width": 100, "height": 100, "properties":
{ "Name": "foo", "Surname": "bar" }}');
But then when I come to use the data item elsewhere in my java-script, the attributes are recognized as a string as opposed to an object. When I hard code the HTML, the data-item is loaded correctly as an object. I have made the assumption it must be because I am incorrectly setting this attribute.
You are getting a string because the property is set as a string, you can get the data as an object after parsing it like so:
var li = document.createElement('li');
li.id = "li1";
li.setAttribute("data-item", '{"width": 100, "height": 100, "properties": { "Name": "foo", "Surname": "bar" }}');
li.innerHTML = "SAMPLE li";
document.body.appendChild(li);
var data = document.getElementById('li1').getAttribute('data-item');
data = JSON.parse(data);
console.log(data);
You can use JSON.parse to turn it into an object :
var result = JSON.parse('{"width": 100, "height": 100, "properties": { "Name": "foo", "Surname": "bar" }}');
// result.width => 100
// result.properties.Name => "foo" etc...
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