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

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

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 Report

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 Report

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