Home  >  Q&A  >  body text

TypeError: Cannot set property 'textContent' to null using textContent

let firstCard = 10;
let secondCard = 4;
let sum = firstCard + secondCard;
let hasBlackJack = false;
let isAlive = true;
let message = ""
let messageEl = document.getElementById("message-el");
let sumEl = document.querySelector("#sum-el");
let cardsEl = document.getElementById("cards-el");
messageEl.textContent = "Do you want to draw a new card?";

function startGame() {
    cardsEl.textContent = "Cards : " + firstCard + " " + secondCard;
    sumEl.textContent = "Sum :" + sum;
    if (sum <= 20) {
        message = "Do you want to draw a new card?";
    } else if (sum === 21) {
        message = "You have got blackjack!";
        hasBlackJack = ture;
    } else {
        message = "You are out of the game!";
        isAlive = false;
    }
    messageEl.textContent = message;
}

P粉310754094P粉310754094378 days ago469

reply all(1)I'll reply

  • P粉969666670

    P粉9696666702023-09-08 16:32:36

    This line:

    let messageEl = document.getElementById("message-el");

    No elements are returned.

    This is because the element does not exist in the DOM when the code is executed. This may be because you don't have any element with that ID, or because you need to move the code to execute after parsing the element into the DOM.

    reply
    0
  • Cancelreply