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

156
Visualizações
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 Respostas
Responde à pergunta

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 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