Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

138
Views
Javascript updates HTML classes before it is expected to

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:

The Pacman Board

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!