skip to Main Content
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;
}

2

Answers


  1. This line:

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

    is not returning an element.

    It is because at the point when the code executes, that element doesn’t exist in the DOM. This could be because you don’t have any element with that ID or because you need to move the code to execute after that element is parsed into the DOM.

    Login or Signup to reply.
  2. Scott Marcus’s answer is right, either the element id is miswritten or you are trying to access it before it was rendered. You can try one of those things below:

    1. Check if the element ID "message-el" from the HTML tag is spelled correctly.

    2. Check if you can move the script to execute below the HTML tag, preferably right before the body closing tag.

    3. Try to wrap your script inside a startUpFunction and execute it after DOM is completely loaded:

       window.addEventListener("DOMContentLoaded", () => {
         startUpFunction()
         //do some stuff
       });
      
    4. In cases where the rendering of elements via Ajax occurs after the DOM is completely loaded, you can try the following trick: write a function that checks if the element is present, if not you wait a few seconds and call the function again recursively:

       let messageEl //Declare global
      
       const delay = ms => new Promise(res => (setTimeout(res, ms)));
      
       async function waitForMessageElLoad() {
           messageEl = document.getElementById("message-el");
           if (!messageEl) { //Not found - wait 500ms and try again.
               await delay(500);
               waitForMessageElLoad();
               return
           }
       }
      

    Hope it helps.
    Cheers!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search