Diego Cespedes Diego Cespedes - 1 month ago 5
HTML Question

Create an HTML list from JSON

I have an array of objects:

enter image description here

I have a div:

<div class="col-lg-12" id="list-puntate">
<!-- Insert my list here -->
</div>


JS

var listDiv = document.getElementById('list-puntate');
var ul = document.createElement('ul');
ul.appendChild(listDiv);
for(var i = 0; i < data.list.length; ++i) {
var li = document.createElement('li');
li.appendChild(data.list[i].puntata);
ul.appendChild(li);
}


I would like to have a result like this:

<div class="col-lg-12" id="list-puntate">
<ul>
<li>values of data.list[i].puntata</li>
<li>...</li>
</ul>
</div>

Answer

You should do as follows:

var listDiv = document.getElementById('list-puntate');
var ul=document.createElement('ul');
for (var i = 0; i < data.list.length; ++i) {
      var li=document.createElement('li');
      li.innerHTML = data.list[i].puntata;   // Use innerHTML to set the text
      ul.appendChild(li);                                 
}
listDiv.appendChild(ul);    // Note here