I am making a Tic-tac-toe game and I have the basic board but I am repeating the code and it is very badly written. I am wondering how I can use better practices to write the DOM elements that I need.
I am referring to the function boardController.buildBoard() which can be found here:
https://github.com/robbiesoho/TTTJS/blob/master/assets/js/script.js
There are nine buttons and here are the first two
const boxOne = document.createElement('div');
boxOne.classList.add('boxOne');
const buttonOne = document.createElement('button')
buttonOne.classList.add("button")
buttonOne.setAttribute('type', 'button');
buttonOne.addEventListener('click', () => {
boxOne.classList.add('token');
boxOne.textContent = playerController.activePlayer;
boardController.board[0] = playerController.activePlayer;
gameController.afterButtonIsPressed();
gameController.winnerAction;
});
const boxTwo = document.createElement('div');
boxTwo.classList.add('boxTwo');
const buttonTwo = document.createElement('button')
buttonTwo.classList.add("button")
buttonTwo.setAttribute('type', 'button');
buttonTwo.addEventListener('click', () => {
boxTwo.classList.add('token');
boxTwo.textContent = playerController.activePlayer;
boardController.board[1] = playerController.activePlayer;
gameController.afterButtonIsPressed();
gameController.winnerAction;
});
I am new to JS and know only enough to know that this is not a good way to write this. Thank you in advance