-1

I am currently building a tic tac toe game with HTML, CSS, and Vanilla JS, and I have a settings button with id 'mode' and class 'settings-button' to toggle between player vs player and player vs cpu (see code below).

When I run document.querySelector on the button's class, it returns a null value, which in turn causes the eventlistener line to raise an error (Uncaught TypeError: Cannot read property 'addEventListener' of null).

I have tried using document.getElementById and putting all of my code into a window.onload block with both document methods, but I experienced the same issue in all scenarios. At first I thought it could be a wifi connection issue, since I am working on repl.it for this project, but I checked other projects that have similar code and they all seemed to be working fine.

I have also tried using document.querySelectorAll, and it returns an empty node list.

What should I do to fix this?

const modeButton = document.querySelector('settings-button');

let cpu = false;

function switchMode() {
  cpu = !cpu;
  this.textContent = cpu ? modeText[1] : modeText[0];
}

modeButton.addEventListener('click',switchMode);
<button id="mode" class="settings-button">Player vs Player</button>
TylerH
  • 20,799
  • 66
  • 75
  • 101
  • This wasn't a duplicate, it is a typo. Your query is `settings-button`, however that looks for elements named `settings-button`. What you meant to query for was `.settings-button` as you were looking for an element with a **class** named "settings-button". – Travis J Jul 09 '20 at 05:32

1 Answers1

0

you are using settings-button as a class instead of .settings-button. add (.) before the class name in querySelector method

const modeButton = document.querySelector('.settings-button');
Zain Ul Abideen
  • 389
  • 7
  • 25