skip to Main Content

So, I am trying to check the value inside an HTML element and use it as a conditional in an if statement in Javascript/TypeScript.

I am trying to do the following: if the element contains "-", you can stop playing, else, click the button and proceed with the game.

I initially created a variable where I could store the element

 const gameButton: string = '#GameButton';

Then I created an if statement where I used gameButton inside the conditional:

if (gameButton.includes("-") {
 console.log("Stop the game")
} else {
console.log("Click button to continue")
}

What is happening is that regardless of the value inside the button, I am still getting the "Click button to continue" message on console each time. What is the correct way of doing this?

2

Answers


  1. Currently you are just checking the static string '#GameButton'. To get the value out of an HMTL element, first you need to get the information about the element with the document.getElementById() browser API. The returned object has a innerText property which holds the text displayed inside the element. Demo:

    if (document.getElementById('GameButton').innerText.includes("-")) {
     console.log("Stop the game")
    } else {
    console.log("Click button to continue")
    }
    <button id="GameButton">Some-Text</button>
    Login or Signup to reply.
  2. You need to first get the content of the element and then check if it contains the specified character. You can use document.querySelector for example

    
    
    const gameButtonElement = document.querySelector('#GameButton');
    
    if (gameButtonElement) {
        // Retrieve the text content of the button
        const buttonText = gameButtonElement.textContent || gameButtonElement.innerText;
    
        // Check if the text includes "-"
        if (buttonText.includes("-")) {
            console.log("Stop the game");
        } else {
            console.log("Click button to continue");
        }
    } else {
        console.log("Game button not found");
    }
    <button id="GameButton">Hello-World</button>

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