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

299
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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