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

292
Visualizações
How can I append a button to all my class

I'm trying to give a button inside all my class .why-text. I selected them by document.querySelectorAll('.why-text'); And use the loop "for" to append button to all the class. But it doesn't working. This is my code:

var btnAddCart = document.createElement("button");

btnAddCart.innerHTML = "Add";

var WhyTxt = document.querySelectorAll('.why-text');

for (let i = 0; i < WhyTxt.length; i++) {
    WhyTxt[i].appendChild(btnAddCart);
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

You create only one button, then keep appending that very same button to n locations, so it ends up in the last of those. Appending an element that is already in the DOM effectively moves that element.

You need to create the button in the loop to have individual buttons:

const WhyTxt = document.querySelectorAll('.why-text');
for (let i = 0; i < WhyTxt.length; i++) {
    const btnAddCart = document.createElement("button");
    btnAddCart.textContent = "Add";
    WhyTxt[i].appendChild(btnAddCart);
}

That being said, your code can also be simplified by alot:

for (let el of document.querySelectorAll(".why-text")) {
  el.append(Object.assign(document.createElement("button"),{textContent:"Add"}));
}
about 4 years ago · Juan Pablo Isaza Relatório

0

You have to create the element each time, within the loop. It could be made outside the looped and cloned within it but you are only making one element in the current structure so it can only be added once.

This working snippet uses the simple approach of making a new button element inside each loop of the parent collection.

var WhyTxt = document.querySelectorAll('.why-text');
console.log(WhyTxt.length);

for (let i = 0; i < WhyTxt.length; i++) {
  var btnAddCart = document.createElement("button");
  btnAddCart.innerHTML = "Add";
  
  WhyTxt[i].appendChild(btnAddCart);
}
div {
height: 2em;
background: yellow;
}
<div class="why-text"></div><br>
<div class="why-text"></div><br>
<div class="why-text"></div><br>
<div class="why-text"></div><br>
<div class="why-text"></div><br>

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