1

I generated an array/list of 9 repeating elements to append to a parent element. When I append the list via the spread syntax, it adds it as a single string. When I use the spread syntax without brackets it appends only as a single item (correctly), this is how the documentation shows as well.

append(...nodesOrDOMStrings)

Below you can see what I have so far:

    const boardContainer = document.querySelector('#gbContainer');
    const boardSquareChild = document.createElement('div');
    boardSquareChild.className = "board-square";
    boardSquareChild.id = "boardSquare";

    boardSqArray = Array(9).fill(boardSquareChild, 0, 9)
    boardContainer.append([...boardSqArray])

Any clue why the brackets make it a single string and without the brackets the element is added singularly? I can't find anything in the documentation as to why (at least not via Mozilla), it doesn't seem to be logical behavior as well.

Greg Iven
  • 171
  • 2
  • 10
  • When the brackets are present, there's only a single argument, when not, the members are spread. But, there's only a single element reference, and `append` moves the element for every argument. You've to create an array of clones. – Teemu Feb 15 '22 at 06:12

2 Answers2

0

I have a work around, but it doesn't answer the question about spread syntax:

for (i = 0; i < boardSqArray.length; i++) {
        let clone = boardSqArray[i].cloneNode();
        boardContainer.append(clone)
    }
Greg Iven
  • 171
  • 2
  • 10
0

The spread operator is working perfectly fine.

The problem you have is you are creating an array filled with a reference to the same exact element. It is not making an array with all new elements. So you are going to either use map or array from and create a new element in each index.

const makeCell = () => {
  const boardSquareChild = document.createElement('div');
  boardSquareChild.className = "board-square";
  return boardSquareChild;
}
const cells = Array.from({ length: 9 }, makeCell);
document.querySelector("#out").append(...cells);
.board-square {
  width: 10px; height: 10px; border: 1px solid black; margin: 1px;
}
<div id="out"></div>

const makeCell = () => {
  const boardSquareChild = document.createElement('div');
  boardSquareChild.className = "board-square";
  return boardSquareChild;
}
const cells = Array(9).fill(0).map(makeCell);
document.querySelector("#out").append(...cells);
.board-square {
  width: 10px; height: 10px; border: 1px solid black; margin: 1px;
}
<div id="out"></div>
epascarello
  • 204,599
  • 20
  • 195
  • 236