Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

257
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda