Home > Software design >  Element.append() multiple elements via spread syntax
Element.append() multiple elements via spread syntax

Time:02-15

I generated a 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 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.

CodePudding user response:

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)
    }

CodePudding user response:

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>

  • Related