removing event listeners for all elements inside html collection

35 Views Asked by At

I am working on this new project in which I need to add and remove event listeners to the HTML collection elements like so:

function Gameboard(){
    const board = [[Cell(),Cell(),Cell()],[Cell(), Cell(), Cell()],[Cell(), Cell(), Cell()]]
    const getBoard = () => board;
    const addToken = (row, column) => {
      board[row][column] = "token";
    } 
    // this is the board display container
    const container = document.querySelector(".container");
    const cells = container.children;

    return {getBoard, addToken, cells}
}

const board = Gameboard()

This is only a portion of the Gameboard function so if you need further clarification I can provide.

The final const board = Gameboard() variable declaration is the one that is used in the below code.

const playGame = () => {
        for (let i=0; i<board.cells.length; i++){
            const listener = (e) => {
                if(e.target.innerText===""){
                    const row = Math.floor(i/3);
                    const column = i%3;
                    board.addToken(row, column, activePlayer.token)
                    if(!checkGameOver()){
                        switchPlayerTurn()
                    }
                    else{
                        for(let j=0; j<board.cells.length; j++){
                            board.cells[j].removeEventListener("click", listener)
                        }
                    }
                }
            }
            board.cells[i].addEventListener("click", listener)
        }
    }

So here I want to remove event listeners for every cells[] element.

I tried to loop through the html collection inside the event listener and remove every event listener but it only removes the event listener of the element that caused the checkGameOver function to be true

0

There are 0 best solutions below