This is a word chain game I made. When the game is over, the text is initialized. Other texts are initialized fine, but the text in span.number-of-people is not. In the console window console.log(numberOfPeople.textContent); It looks like it has been initialized. But why is the number not erased from the screen?
const numberOfPeople = document.querySelector(".number-of-people"); const previousWord = document.querySelector(".previous-word"); const inputWord = document.querySelector("#input-word"); const submitButton = document.querySelector("#submit-button"); let number = parseInt(prompt("How many people are participating in the game?")); let word; const gameStart = () => { if(number) { numberOfPeople.textContent = number; } else { number = parseInt(prompt("Please enter a number.")); gameStart(); } } gameStart(); const onClickSubmitButton = (e) => { e.preventDefault(); word = inputWord.value; if (inputWord.value.length < 3) { alert("Please enter 3 or more characters and less than 10 characters.") } else if ((previousWord.textContent === "") || (previousWord.textContent[previousWord.textContent.length - 1] === word[0])) { previousWord.textContent = word; inputWord.value = ""; inputWord.focus(); } else { alert("GAME_OVER"); inputWord.value = ""; previousWord.textContent = ""; console.log(numberOfPeople.textContent); // The result of this code is number of people. numberOfPeople.textContent = ""; // This code is not working. console.log(numberOfPeople.textContent); // The result of this code is "". gameStart(); return; } } submitButton.addEventListener("click", onClickSubmitButton);
<!DOCTYPE html> <html> <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"> <title>word-chain game</title> <script src="js/word-chain_game.js" defer></script> </head> <body> <div class="word-chain__wrapper"> <h4>number-of-people : <span class="number-of-people"></span></h4> <h4>previous-word : <span class="previous-word"></span></h4> <form> <label for="input-word">enter a word</label> <input name="input-word" id="input-word" type="text" required minlength="3" maxlength="10" placeholder="Please enter a word."> <input id="submit-button" type="submit" value="input"></input> </form> </div> </body> </html>
Advertisement
Answer
It is working. But then you’re calling gameStart()
. Which does this:
if(number) { numberOfPeople.textContent = number; }
So the code is successfully clearing the text in that element and then immediately putting it back again.
You probably also meant to reset the number
variable when ending the game:
numberOfPeople.textContent = ""; number = null;
Keep in mind of course that this will likely lead you to start re-thinking some UX. Because while this “works”, the use of prompt()
will block the UI from updating, and then immediately after promt()
the new value is again used. So the code still never visually empties that field.