Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML SetAttribute with nested properties

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.

like image 715
Stinkidog Avatar asked Oct 17 '22 07:10

Stinkidog


2 Answers

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);
like image 158
Shakti Phartiyal Avatar answered Nov 01 '22 16:11

Shakti Phartiyal


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...
like image 42
MrGeek Avatar answered Nov 01 '22 17:11

MrGeek