HTML SetAttribute with Nested Properties

I’m sure that they will answer something to this, but I don’t have enough knowledge of terminology that can’t find where to look.

I am dynamically creating Html as a result of some json data downloaded from the server.

I use createElement and setAttribute to create html and add it to the main body.

However, my dynamic html contains the "data-" attribute, which has additional nested properties. An example of an ultimate goal is:

<li>
   <span class=item data-item='{"width": 100, "height": 100, 
    "properties": { "Name": "foo", "Surname": "bar" }}'></span>
</li>

I had some success at startup:

li.setAttribute("data-item", '{"width": 100, "height": 100, "properties": 
                 { "Name": "foo", "Surname": "bar" }}');

, java- script, , . HTML, . , , .

+4
2

, , :

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);
Hide result
+2

JSON.parse, :

var result = JSON.parse('{"width": 100, "height": 100, "properties": { "Name": "foo", "Surname": "bar" }}');
// result.width => 100
// result.properties.Name => "foo"     etc...
+1

Source: https://habr.com/ru/post/1683241/


All Articles