Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

193
Visualizações
Why isn't my list updated when I add new items to the array?

I'm stuck. Trying to push input values into an array, which actually works, but then I want to get them out into an unordered list, and they don't show up. What am I doing wrong?

const inputBtn = document.querySelector("#input-btn");
let myLeads = [];
const inputEl = document.querySelector("#input-el");
const ulEl = document.querySelector("#ul-el");

inputBtn.addEventListener("click", function() {
  myLeads.push(inputEl.value);
  console.log(myLeads);
});

for (let i = 0; i < myLeads.length; i++) {
  ulEl.innerHTML += "<li>" + myLeads[i] + "</li>";
}
<input type="text" id="input-el" />
<button id="input-btn">SAVE INPUT</button>
<ul id="ul-el"></ul>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Your loop doesn't do much because it's executing before any clicks.

Remove the dependence on the array, and use insertAdjacentHTML to add the wrapped value of the input directly to the list within the click handler.

(Note: I'm using insertAdjacentHTML here because there are performance issues that arise from concatenating HTML to an element's innerHTML property.)

const inputBtn = document.querySelector('#input-btn');
const inputEl = document.querySelector('#input-el');
const ulEl = document.querySelector('#ul-el');

inputBtn.addEventListener('click', function() {
  ulEl.insertAdjacentHTML('beforeend', `<li>${inputEl.value}</li>`);
});
<input type="text" id="input-el" />
<button id="input-btn">SAVE INPUT</button>
<ul id="ul-el"></ul>

Additional documentation

  • Template/string literals
about 4 years ago · Juan Pablo Isaza Relatório

0

One option would be to immediately call your for loop right after pushing to the array. Like so:

inputBtn.addEventListener("click", function() {
  myLeads.push(inputEl.value);
  for (let i = 0; i < myLeads.length; i++) {
     ulEl.innerHTML += "<li>" + myLeads[i] + "</li>";
  }
  console.log(myLeads);
});

Right now, the for loop isn't run at all.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda