Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

192
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda