The problem
I am making Pacman, and I wrote the following function to initialize the board. How is it possible that the board is rendered, even though I only add the styling classes to the square elements in my 'squares' array? As far as I can see I never updated the classes of the div elements inside my 'grid' (which holds the actual div html elements that are shown to the user).
The function
function createBoard() {
for (let i = 0; i < layout.length; i++) {
const square = document.createElement('div')
grid.appendChild(square)
squares.push(square)
if (layout[i] === 0) {
squares[i].classList.add('pac-dot')
} else if (layout[i] === 1) {
squares[i].classList.add('wall')
} else if (layout[i] === 3) {
squares[i].classList.add('power-pellet')
}
}
}
The function iterates through an array (layout) that holds information of how the board should look. For each element of that array a div (square) is created which is then added to the 'grid' (a div element in my html file that holds all newly created divs). The square div is then added to the 'squares' array, which also holds all the square divs, but is not present in my html file.
The second part of the function adds a class to the square in the squares array , based on how the board should look. The result is the following board:
Assuming grid is a DOM element, then grid.appendChild(square) will add the square to the DOM. After that, any change you apply to the element's style will be visible.
So for example, let's say you have the following HTML:
<div id="grid"></div>
Now let's add a child div to it:
const grid = document.getElementById("grid");
const square = document.createElement("div");
grid.appendChild(square);
This actually changes the HTML, to be as if it was written like this:
<div id="grid">
<div></div>
</div>
Adding a class to the div will also change the markup. So after this:
square.classList.add('wall');
The HTML will look like so:
<div id="grid">
<div class="wall"></div>
</div>