• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

215
Vistas
How do I add child <li> elements to <ul> without removing current children

How do I iteratively add children elements to a (for example) a .

<ul id="my-list">
   <li>item 1</li>
   <li>item 2</li>
</ul>

If I have a JS script that runs something like this several times:

document.getElementById('my-list').appendChild('someListItemICreated')

the current 2 list items are removed. How do I add new li items to the ul without losing the current list itmes?

almost 3 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

You need to provide an element as the argument for appendChild and not a string. Like this:

const li = document.createElement("li");
li.innerText = "Item 3";
document.getElementById("my-list").appendChild(li);
<ul id="my-list">
  <li>Item 1</li>
  <li>Item 2</li>
</ul>

A much easier and a cleaner approach that I prefer in most of cases is:

document.getElementById("my-list").innerHTML += "<li>Item 3</li>";
<ul id="my-list">
  <li>Item 1</li>
  <li>Item 2</li>
</ul>

almost 3 years ago · Juan Pablo Isaza Denunciar

0

I think you need to be more specific with what your code is actually doing, but I can say that someListItemICreated should not be a string, if that's what you're passing. Here's an example I made that's similar to what you're referring to that runs fine.

<ul id="my-list">
  <li>Item 1</li>
  <li>Item 2</li>
</ul>
let someListItemICreated = document.createElement("li");
someListItemICreated.appendChild(document.createTextNode("item 3"));

document.getElementById("my-list").appendChild(someListItemICreated)
almost 3 years ago · Juan Pablo Isaza Denunciar

0

const c = document.createElement('li');
c.innerText = 'item 3';
document.getElementById('my-list').appendChild(c);
<ul id="my-list">
   <li>item 1</li>
   <li>item 2</li>
</ul>

almost 3 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 Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda