Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

291
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!