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

163
Views
Using Javascript with CSS Grid

I am trying to use a JavaScript for loop to auto-generate a 4 by 4 CSS grid. None of the grid items are appearing, except for the light blue background. I am using the appendChild() and setAttribute() functions in two separate for loops: one for rows and one for columns. HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>replit</title>
    <link href="style.css" rel="stylesheet" type="text/css" />
  </head>
  <body>
        <div class="grid-container" id="grid">
        </div>
    <script src="script.js"></script>
  </body>
</html>

JS:

const grid = document.getElementById("grid");

for(let i = 1; i < 5; i++)
{
    for(let x = 1; x < 5; x++)
    {
        var item = document.createElement("div");
        //item.setAttribute("style", "grid-area:" + i + " / " + x + " / " + i + " / " + x);
        item.setAttribute("grid-column", x + " / span 1");
        item.setAttribute("grid-row", i + " / span 1");
        item.setAttribute("class", "grid-item");
        grid.appendChild(item);
    }
}

CSS:

.grid-container {
    display: grid;
    /*width: 50%;
    height: 100%;*/
    grid-template-columns: 30px 30px 30px 30px;
    grid-template-rows: 30px 30px 30px 30px;
    gap: 10px;
    background-color: lightblue;
}

#grid-item {
    background-color: blue;
    border-style: solid;
  border-width: 5px;
    border-color: red;
}
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

In CSS change your set Attribute from class to id

item.setAttribute("id", "grid-item");

Because in css when you use # it's mean ID but when you use . its mean Class

enter image description here

Ref : https://www.w3schools.com/cssref/css_selectors.asp

about 4 years ago · Juan Pablo Isaza Report

0

You just have to change your css for grid-item from id selector to class selector. i.e.,

.grid-item {
    background-color: blue;
    border-style: solid;
  border-width: 5px;
    border-color: red;
}

enter image description here

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!