Adding 100 buttons in a div

Viewed 126

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.

3 Answers

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.

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

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

Related