Search code examples
javascripthtmlcssdomcss-grid

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

Solution

  • 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