0

I'm trying to make a game and every time a button is pressed, I want to change the backgroundColor of divs inside a list.

This is my error message

Uncaught TypeError: Cannot read property 'style' of undefined

This is my JavaScript

var difficulty;
var btnChosen = document.querySelectorAll("button")
var squares = document.querySelectorAll(".square")
var colors = []

for (var i = 0; i < btnChosen.length; i++) {
    btnChosen[i].addEventListener("click", function() {
        if (this.textContent === "Normal") {
            difficulty = 6
            for (var i = 0; i < difficulty; i++) {
                colors[i] = "rbg("+pickRandom(255)+", "+pickRandom(255)+", "+pickRandom(255)+")"
                squares[i].style.backgroundColor = colors[i]
                console.log(colors[i])
                console.log(squares[i])
            }
            console.log(difficulty)
            console.log(colors)
        }
    })
}

This is my HTML

<div>
    <span id="message"></span>
    <button>Normal</button>
</div>

    <div id="container">
        <div id="normal-mode" class="square"></div>
        <div id="normal-mode" class="square"></div>
        <div id="normal-mode" class="square"></div>
        <div id="normal-mode" class="square"></div>
        <div id="normal-mode" class="square"></div>
        <div id="normal-mode" class="square"></div>
    </div>
Vicdenz
  • 27
  • 5

1 Answers1

1

Change document.querySelectorAll to document.querySelector. You don't have to use document.querySelectorAll since it is only one button. It will be ideal to give the button element an id. Thus <button id="id-here">Some text</button> and reference it using document.querySelector("#id-here"). Change remove btnChosen[i] to btnChosen because the variable only contains one element not many.

Get rid of for (var i = 0; i < btnChosen.length; i++). It is not needed.