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

319
Visualizações
Adding 100 buttons in a div

I am following along a Javascript tutorial and I have to add in 100 buttons inside of a div using Javascript.

At first, I tried doing something like this:

const btn = document.createElement('button');
const div = document.querySelector('div');
btn.innerText = 'Hey!';
for (let i = 0; i < 100; i++) {
    div.appendChild(btn);
}

And this ended up only making 1 button. However, if I repeat the same code it just appends buttons after the previous one. However, this approach:

for (let i = 0; i < 100; i++) {
    const btn = document.createElement('button');
    const div = document.querySelector('div');
    btn.innerText = 'Hey!';
    div.appendChild(btn);
}

does the job. I can't seem to understand why the 2nd one works and the 1st one doesn't.

From my understanding, the first approach seemed better because I wasn't making the same variables over and over again. However that only ends up in me making just one button instead of 100.

about 4 years ago · Santiago Gelvez
3 Respostas
Responde à pergunta

0

First example won't work, cause it is just how method appendChild works. According to MDN. It just moves the node/element from its current position to specified. So your first example is just renewing the position of only one node, cause you've created only one div

Second example creates div every time, so it is a new element, which is stored inside your parent element.

about 4 years ago · Santiago Gelvez Relatório

0

The code that creates element is document.createElement and You call it ones in first example, hence only one element is created.

appendChild does not creates an element, it appends already created element to some parent.

If it is already appended, then does nothing

about 4 years ago · Santiago Gelvez Relatório

0

because in the first case you are trying to append the same DOM object 100 times, but have to create a new one each time

about 4 years ago · Santiago Gelvez 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