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

184
Vistas
why is appendChild not working on <li> template tag

I have this JS and HTML content:

const parent = document.querySelector('#parent');
const choices = parent.dataset.choices.split(",")

const childTplt = document.querySelector('#children');
for (c of choices) {
  let child = childTplt.content.cloneNode(true);

  child.appendChild(document.createTextNode(c));
  parent.appendChild(child);
}
<ul id="parent" data-choices="one,two,three">
</ul>
<template id="children">
   <li> </li> 
</template>

and end up with this on my page:

<ul id="parent" data-choices="one,two,three"> 
  <li> </li> 
one
  <li> </li> 
two
  <li> </li> 
three</ul>

Why is that text content ends up as sibling of <li> and not as an actual children (inside of <li></li> ?

thanks for your input!

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

The .content property of a template element is a document fragment; it is not the <li> element. In your case, the template is simple, so you can just reference the first child of the fragment:

  let child = childTplt.content.firstElementChild.cloneNode(true);
about 4 years ago · Juan Pablo Isaza Denunciar

0

This worked for me

function function1() {
  var ul = document.getElementById("list");
  var li = document.createElement("li");
  li.appendChild(document.createTextNode("Four"));
  li.setAttribute("id", "element4"); 
  ul.appendChild(li);
  alert(li.id);
}
about 4 years ago · Juan Pablo Isaza Denunciar

0

In the loop above, you are appending c (one, two, three), then appending a cloned version of what is inside #children.

for (c of choices) {
  let child = childTplt.content.cloneNode(true);

  child.appendChild(document.createTextNode(c)); //will append 'one'
  parent.appendChild(child); //will append <li></li>
}

You can replace it with this loop and it will do what you are aiming for:

for (c of choices) {
    let li = document.createElement('li');
    li.append(c);
    parent.append(li);
}
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