mount HTML element with vanilla JS, I can not list all elements of JSON

1

Where is the error in my code?

I am not able to list all the names in a <li> different, in my console.log(items[i].name) all the names of the JSON appear, however at the time of creating the html element it only takes the last name.

const myList = fetch('people.json')
.then(response => response.json())
.then(result => {
  const items = result.data;

  for(let i = 0; i < items.length; i++) {
    let people = document.getElementById("people");

    console.log(items[i].name)
    
    const markup = '
      <li>
        ${items[i].name}
      </li>
    ';

    people.innerHTML = markup;
  }
})
.catch(err => {
  console.log("Erro");
});
    
asked by anonymous 04.10.2017 / 18:33

1 answer

2

You forgot a + .

people.innerHTML += markup;

In any case, I suggest at least that you remove .innerHTML = markup from your loop, this operation is very costly.

let markup = "";
let people = document.getElementById("people");
for(let i = 0; i < items.length; i++) {
  console.log(items[i].name);
  markup += '
    <li>
      ${items[i].name}
    </li>
  ';
}
people.innerHTML = markup;

And finally I'm in a Vibe of using VueJS for everything; D

var app = new Vue({
  el: '#app',
  data: {
    passo: "Iniciando a aplicação",
    nomes: [ "Fulano", "Ciclano", "Beltrano" ]
  }
});

// inserir novo nome apos 2 segundos.
window.setTimeout(function () {
  app.passo = "inserindo novo nome apos 2 segundos.";
  app.nomes.push("Toby Mosque");
}, 2000);

// atualizar toda a lista apos 4 segundos
window.setTimeout(function () {
  app.passo = "atualizando toda a lista apos 4 segundos.";
  app.nomes = [ "Eric", "Toby Mosque" ]
}, 4000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.4.4/vue.min.js"></script><divid="app">
  <p>passo: {{passo}}</p>
  <ul v-for="(nome, indice) in nomes">
    <li>{{indice}} - {{nome}}</li>
  </ul>
</div>
    
04.10.2017 / 18:35