0

I am trying to find out why createElement or maybe appendChild doesn't work Does every createElement have some kind of unique id?

Works - 4 buttons

 const arr = [1, 2, 3, 4];
 const list = document.getElementById('list');
 arr.map(item => {
     const newButton = document.createElement('button');
     newButton.innerHTML = `Button`;
     list.append(newButton)
 });

Doesn't work - only 1 button it seems it would work to me...

 const list2 = document.getElementById('list2');
 const newButton2 = document.createElement('button');
 newButton2.innerHTML = `Button2`;

 arr.map(item => {
    list2.append(newButton2);
 });
  • Please, show us your HTML code as well – aca Jul 14 '22 at 12:54
  • 1
    You create one button. Appending ot doesn't create a new one. That's one of the good things about the DOM. To move an existing element you just append it somewhere, no need to remove it from where it currently is. Same goes for newly created elements – Jaromanda X Jul 14 '22 at 12:55
  • 3
    It is because you are appending the same button over and over. A single element can only live in one place in the DOM. You need to clone it. [cloneNode](https://developer.mozilla.org/en-US/docs/Web/API/Node/cloneNode) – epascarello Jul 14 '22 at 12:56
  • 1
    You should be using [`forEach` or `for...of`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Loops_and_iteration) for this, not `map`. `map` returns a new array. – Andy Jul 14 '22 at 12:56

0 Answers0