skip to Main Content

I would like to try and confirm the winner of the game. To do this I was planning on using document.getElementById('player1').innerText === 0 to check if player 1 score was equal to zero, but I think the syntax is wrong above. How would I check if the innerText is equal to zero?

function checkWinner() {
    if (document.getElementById('player1').innerText === 0) {
        message.innerHTML = `<p>${players[1]} you have won the game</p>`;
    }
    if (document.getElementById('player2').innerText === 0) {
        message.innerHTML = `<p>${players[0]} you have won the game</p>`;
    }
}

3

Answers


  1. You should probably just do === "0" instead.

    innerText can never be a number, it will always be a string.

    Login or Signup to reply.
  2. The problem is that you’re comparing using the === (Strict equal) operator that will compare operands type too.

    The Element.innerHtml will always return a string, not a number.

    So your comparison is false:

    "0" === 0 // false
    

    The correct is that you compare against a zero string:

    function checkWinner() {
        if (document.getElementById('player1').innerText === "0") {
            message.innerHTML = `<p>${players[1]} you have won the game</p>`;
        }
        if (document.getElementById('player2').innerText === "0") {
            message.innerHTML = `<p>${players[0]} you have won the game</p>`;
        }
    }
    
    Login or Signup to reply.
  3. As other have said, innerHTMLL will be a String, but you may convert it to numeric by adding a + sign

      if (+document.getElementById('player1').innerText === 0) {
            message.innerHTML = `<p>${players[1]} you have won the game</p>`;
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search