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

150
Vistas
i think that the code is the same but i don't know why it make different results

Why does the code make difference output and it is almost the same input? Input:

var Add = document.getElementById('AddElement'); //the button
var Element = document.getElementById('element'); // the input text
var ListParent = document.querySelector('ul');
    
Add.addEventListener('click', function(){
    var AddText = document.createElement('li').appendChild(document.createTextNode("hello"));
    ListParent.appendChild(AddText);
})

Output:

first click: hello

second click: hellohello

Input:
var Add = document.getElementById('AddElement');
var Element = document.getElementById('element');
var ListParent = document.querySelector('ul');
    
Add.addEventListener('click', function(){
    var AddText = document.createElement('li');
    AddText.appendChild(document.createTextNode('hello'));   
    ListParent.appendChild(AddText);
})

Output: first click:

  • hello

second click:

  • hello
  • hello
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

appendChild returns the appended node:

const div = document.createElement('div');
const parent = document.createElement('div');
const result = parent.appendChild(div);
console.log(result === div);

So when you do

var AddText=document.createElement('li').appendChild(document.createTextNode("hello"));
                                         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

The value put into addText is the created text node. In contrast, with

var  AddText = document.createElement('li');

it's the <li>, not the text node.

So, with the first approach, the created <li> doesn't get used (and probably isn't what you want).

If you wanted to use the <li>, and slim your code down, assign to the .textContent of the <li> instead.

Add.addEventListener('click', function(){
    ListParent.appendChild(document.createElement('li'))
      .textContent = element.value;
})
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