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>
CodePudding user response:
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 = "";
}
}