Creating Square Divs and Hovering Them

I am trying to create nxn grid of square divs and when the user hovers over squares they will change color randomly. At the bottom of the page there will be “clear” button which reloads the page. I have two problems here:

  1. Hovering is not working.
  2. I can’t move “clear” button to below the grid.

Here is the code: https://codepen.io/krykck/pen/wvaMMzW

@krykck You have a few problems:

  1. You attempting to add event listeners before the grid has been created (i.e. you call the makeRows function after you have tried to add the event listeners).

  2. The following code is not selecting any elements. Research how to use querySelectorAll.

var = squares=document.getElementById("container").getElementsByClassName(".grid-item");
  1. In the following line, i will reference an element that does not exist. You can either research how to make use of the event object that gets passed to the event listener or think about how you could use this here.
squares[i].style.backgroundColor=bgColor;

You can add a console.log(i) before the above line, to see what i’s value is.

1 Like

To center the button, you can use:

.clear {
  margin: auto;
  display: block;
}

Thanks a lot for the explanation! If I understand correctly getElementsByClassName returns HTMLCollections rather than NodeLists and thats why it doesn’t work. But I don’t understand what you mean by it is not selecting any elements.

No, you could have used getElementsByClassName, but you would need to remove the dot before the class name.