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.