Как очистить содержимое innerHTML HTMLCollection?

Я создаю игру Tic Tac Toe. Моя проблема заключается в том, что я не могу очистить innerHTML от нескольких div (класс div .cell) при нажатии кнопки resetButton. Элементы div, которые я пытаюсь очистить, являются дочерними элементами gameDisplay.

Когда я попытался найти элементы ячейки в своем инструменте разработчика Chrome, я получаю коллекцию HTML: Скриншот здесь

У меня возникают трудности с доступом к innerHTML этих элементов. В настоящее время у меня есть функция resetGame(), возвращающая gameDisplay.innerHTML=""(строка 79), которая удаляет все содержимое родительского элемента и полностью удаляет мою сетку (доску). Я знаю, что это недостаточно конкретно. В результате я попытался вернуть gameDisplay.children.innerHTML =""; вместо этого ничего не происходит в DOM или в моей консоли chrome dev tools.

Как я могу получить доступ к innerHTML этих div и удалить HTML внутри них с помощью функции resetGame?

JS

const playerFactory = () => {
    const playTurn = (event, currentPlayer) => {
      const id = boardObject.cells.indexOf(event.target);
      boardObject.boardDisplay[id] = currentPlayer;
      boardObject.render();
    };
  
    return {
      playTurn
    };
  };
  
  // Gameboard object
  const boardObject = (() => {
    let boardDisplay = ['', '', '', '', '', '', '', '', ''];
    const cells = Array.from(document.querySelectorAll(".cell"));
    // displays the content of the boardArray
    const render = () => {
      boardDisplay.forEach((cells, idx) => {
        cells[idx].innerHTML = boardDisplay[idx];
      });
    };
    return {
      boardDisplay,
      render,
      cells
    };
  })();


  // Create Array from DOM
const boardArray = [...document.querySelectorAll(".cell")].map(cells=>cells.innerHTML);
console.info(boardArray);

// Display controller, shows which player is which
const displayController = (() => {
const playerOne = 'X';
const playerTwo = 'O';
const gameBoard = document.querySelector(".game-board");
let currentPlayer = playerOne;

const switchPlayer = () => {
    currentPlayer = currentPlayer === playerOne ? playerTwo : playerOne;
  }

  gameBoard.addEventListener("click", (event) => {
    if (event.target.classList.contains("cell")) {
      if (event.target.textContent === "") {
        event.target.textContent = currentPlayer;
        const indexOfClickedCell = Array.prototype.indexOf.call(document.querySelectorAll('.cell'), event.target);
        boardArray[indexOfClickedCell] = currentPlayer;
        switchPlayer();
             
   
      }
    }
  });
})();


const gameDisplay = document.getElementById("game-board");


// Define reset button function first
function resetGame(){

// Define result, reset the board
//if the board array index is equal to a character
if (boardArray.includes('X','O')){
    { return gameDisplay.innerHTML = "";
       
      }
}
else
  {;}
//and if the cells textContent is equal to a character
//return the result, which is the reset board function 
}

const resetButton = document.querySelector(".restart");
resetButton.addEventListener("click", (event) => {
    resetGame(event);
});

HTML

<!DOCTYPE html>
<html lang = "en">
<head>
    <meta charset = "UTF-8">
    <meta http-equiv = "X-UA-Compatible" content = "IE=edge">
    <meta name = "viewport" content = "width=device-width, initial-scale=1.0">
    <link rel = "stylesheet" href = "https://use.typekit.net/xtq6hun.css">
    <link rel = "stylesheet" href = "styles.css">
    <title>TIC-TAC-TOE</title>
</head>
<body>
    <main>
<div class = "top-text">
<h1>TIC TAC TOE</h1>
<div id  = "game-text">
</div>
</div>
<div class = "game-board" id = "game-board">
<div class = "cell" id = "cell-1"></div>
<div class = "cell" id = "cell-2"></div>
<div class = "cell" id = "cell-3"></div>
<div class = "cell" id = "cell-4"></div>
<div class = "cell" id = "cell-5"></div>
<div class = "cell" id = "cell-6"></div>
<div class = "cell" id = "cell-7"></div>
<div class = "cell" id = "cell-8"></div>
<div class = "cell" id = "cell-9"></div>
</div>
<div class = "bottom-box">
<button class = "restart">RESTART GAME</button>
</div>
    </main>
<script src = "script.js" defer></script>
</body>
</html>

CSS

/*CSS RESET*/
* {
margin:0;
padding:0;
}

body {
background-color: #faf9fa;
}

main {
display: flex;
align-content: center;
flex-direction: column;
flex-wrap: nowrap;
justify-content: center;
align-items: center;
}

h1 {
font-family: blackest-text, sans-serif;
font-weight: 700;
font-style: normal;
font-size: 60px;
color: #38393a;
}

h2 {
font-family: elza, sans-serif;
font-weight: 500;
font-style: normal;
font-size: 20px;
color: #38393a;
}

.top-text {
border: none;
margin: 0.5em;
display: flex;
flex-direction: column;
align-items: center;
}

.game-board {
display: grid;
grid-template-columns: repeat(3, 1fr);
border: 1px solid #38393a;
margin: 0px auto;
background-color: #faf9fa;
margin-bottom: 2em;
}

.cell:hover {
background-color: rgb(221, 253, 228); 
}

.cell {
/*STYLING X'S AND O'S*/    
font-family: blackest-text, sans-serif;
font-weight: 700;
font-style: normal;
font-size: 100px;
color: #38393a;
/*STYLING INDIVUAL CELLS*/
min-height: 170px;
min-width: 170px;
border: 1px solid #38393a;
display: flex;
align-content: center;
flex-wrap: nowrap;
justify-content: center;
align-items: center;
}

img {
width: 90px;
color:#38393a;
}

.message-display {
border: none;
margin-bottom: 1em;
}

.restart{
font-family: elza, sans-serif;
font-weight: 500;
font-style: normal;
height: 3.5em;
width: 12em;
border-radius: 30px;
border: 1px solid #38393a;
background-color: #faf9fa;
padding: 1px;
}

.restart:hover{
background-color: rgb(221, 253, 228);
}

span {
    font-family: blackest-text, sans-serif;
    font-weight: 700;
    font-style: normal;
    font-size: 100px;
    color: #38393a;
    }

p {
    font-family: blackest-text, sans-serif;
    font-weight: 700;
    font-style: normal;
    font-size: 30px;
    color: #38393a;
}


.children возвращает массив, который вам нужно зациклить, и установить innerHTML как пустой

risky last 26.11.2022 20:34
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
0
1
108
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

В вашей функции resetGame вы должны перебрать все ячейки и удалить их содержимое вместо удаления всего содержимого игрового поля.

for(let i =0;i < gameDisplay.children.length;i++) {
    gameDisplay.children[i].innerHTML = '';
}

Другие вопросы по теме