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

198
Views
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 answers
Answer question

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