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

271
Visualizações
How to add new <li> element each click?

First attempt at any sort of Javascript so be gentle aha

Have managed to have the page add the new list item to the inner html of an unordered list, but each time after that it just replaces the initial.

I feel like I'm missing something really basic here?

Any advice would be greatly appreciated.

    <script>
        function addItem() {
            var item = document.getElementById("task-field").value;
            document.getElementById("task-list").innerHTML = "<li> " + item + " </li>";
        }
    </script>

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

0

<script>
  function addItem(item) {
    const li = document.createElement('li');
    li.innerHTML = `${item}`;
    li.id = 'task-field';
    document.getElementById('task-list').appendChild(li);
  }
</script>
about 4 years ago · Juan Pablo Isaza Relatório

0

Use

document.getElementById("task-list").innerHTML += "<li> " + item + " </li>";

instead of

document.getElementById("task-list").innerHTML = "<li> " + item + " </li>";

The += operator will use the current value of innerHTML and append your new content in this case. This as suggested by @Hassam Imam.

Another way of doing it is using appendChild() creating the new <li> item through JS. Like this:

function addItem() {
    let item = document.getElementById("task-field").value;
    let parent = document.getElementById("task-list");
    
    // Create new node.
    let li_item = document.createElement("li");
    li_item.innerHTML = item;
    
    // Append child.
    parent.appendChild(li_item);
}

But this last method is probably too lengthy. The += solution seems good. Just another way of doing it.

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