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

195
Vistas
How to clear a javascript generated grid of div elements of an applied background color

Within my program I am generating a grid of fields and assigning them the className of "grid-item". I have an event listener applied for mouseover. As the mouseover occurs, the background color of the respective "grid-item" has a new background color applied.

I am trying to make a clear button that will reset all of these background colors to "" but I keep getting the error "Uncaught TypeError: Cannot set properties of undefined (setting 'backgroundColor')" and am at a loss.

I believe that my issue lies in my onClick function not being able to find "grid-item".

Can anyone point me in the right direction without explicitly giving me the answer?

javascript

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

function makeRows(rows, cols) {
    container.style.setProperty('--grid-rows', rows);
    container.style.setProperty('--grid-cols', cols);
    for (c = 0; c < (rows * cols); c++) {
        let cell = document.createElement("div");
        cell.addEventListener("mouseover", function(event){
            event.target.style.backgroundColor = "orange";
        } )
        container.appendChild(cell).className = "grid-item";    
        
        }
             

    };


    let clear = document.getElementById("clearBtn");
    clear.onclick = function(){
        document.getElementsByClassName('grid-item').style.backgroundColor = "";
    }

makeRows(16, 16); 

declaration of button in the HTML file

<button id = "clearBtn">Clear</button>
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

document.getElementsByClassName('grid-item')returns you the array of elements, so you cannot use .style property from it.

updated code: https://jsfiddle.net/4r18o97v/1/

let clear = document.getElementById("clearBtn");
    clear.onclick = function(){
     var elements = document.getElementsByClassName('grid-item');
        for (var i = 0; i < elements.length; i++) {

          elements[i].style.backgroundColor = "";

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