-1

Stumped here. When I try calling this.makeBoard(); it gives my a type error. Any help would be appreciated. I did not include my other methods, they give the same errors however.

Error: TypeError: this.makeBoard is not a function at HTMLInputElement

class Game {
  constructor() {
    this.init();
  }

  init() {
    this.board = [];
    this.currPlayer = 1;
    this.button = document.querySelector("#submit");
    this.button.addEventListener('click', function(e){
      e.preventDefault();
      const htmlBoard = document.querySelector('#board');
      this.width = parseInt(document.querySelector('#width'));
      this.height = parseInt(document.querySelector('#height'));
      while (htmlBoard.firstChild) {
        htmlBoard.removeChild(htmlBoard.firstChild)
      }
      this.makeBoard();
    });
  }

  makeBoard() {
    for (let y = 0; y < this.height; y++) {
      this.board.push(Array.from({ length: this.width }));
    }
  }
}

new Game();
Brandon
  • 31
  • 4
  • Because you have no element with `id="submit"` in your document when this code runs – Phil Jul 20 '21 at 13:31
  • Please include the full error message in your question. _"it gives my a type error"_ is not enough to go on – Phil Jul 20 '21 at 13:32
  • I can include the HTML inside of the code snippet as well if you'd like. However, the submit button is included in the HTML already along with a form for user input. the whole init() function works, EXCEPT calling other methods – Brandon Jul 20 '21 at 13:34
  • Ah, you're trying to access `this` inside the event handler. See the linked duplicate – Phil Jul 20 '21 at 13:36

1 Answers1

1

document.querySelector() returns an element object not a string. You can get the content of the element using .innerText

In your example change the this.width and this.height declarations to.

this.width = parseInt(document.querySelector('#width').innerText)
this.height = parseInt(document.querySelector('#height').innerText)
lejlun
  • 4,140
  • 2
  • 15
  • 31