skip to Main Content

I´m starting to learn JS, so I have very basic questions about it…

In this case, I´m trying to do a "tennis points" counter. So, I made that, and when some player gets to 45 points, the app shows a "player 1 won the set"

The problem is… I want to take that "player 1 won the set", and when it appears, I want to show an alert saying "do you want to play another set?" But I can´t do it…

I have this blank

en HTML. I wrote the JS code, so when a player reaches 45 points, the

turns in "player 1 won the set"

            <p id="winner1"></p>

Then, I tried to "get" that new string and create an alert


let winner1 = document.getElementById("winner1")

if(winner1 == "player 1 won the set"){
alert("do you want to play another set?")
}

But it doesn´t work. I tried with winner1.value, but it doesn´t work either.
It seems like I need something that is always "listening" the

value, but I don´t know how to do it…

Sorry for the so basic question.

Thanks in advance!

2

Answers


  1. It’s a bad idea, but you could try this

    if(winner1.innerText == "player 1 won the set"){
    alert("do you want to play another set?")
    }
    

    It would be much better to avoid reading from the screen like this

    Store the status in a variable, rather than inside the DOM. That would be simpler, more conventional, clearer for the programmer who maintains your code, and less vulnerable to bugs (e.g. when you change the wording of the screen message).

    Login or Signup to reply.
  2. HTMLElement.innerText should work, But again it’s not a good practice to compare the DOM innerText values to perform some operations. But if still if you want that in a same way, You can achieve like this :

    // Just for a demo purpose I am hardcoding this, But you update this variable as per the logic and then use this variable while checking for the condition to show the alert.
    let winnerMessage = 'Player 1 won the set'
    
    const msgElement = document.getElementById('winner1');
    msgElement.innerText = winnerMessage;
    
    if(winnerMessage === "Player 1 won the set"){
      alert("do you want to play another set?")
    }
    <p id="winner1"></p>

    More optimal and suggested solution is to bind the message along with the confirmation alert.

    let winnerMessage = 'Player 1 won the set'
    
    if (winnerMessage) {
        alert(`${winnerMessage}, do you want to play another set?`);
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search