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
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 thedocument.getElementById()
browser API. The returned object has ainnerText
property which holds the text displayed inside the element. Demo: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