Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

165
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda