0

I am doing a 'if,else' statement in javaScript. I want to change the "h2" text. I think I'm missing some code

<div id="game"> 
  <p id="howMany">How many fingers am I holding up?</p> 
  <p id="theGame"> <input type="guess" id="guess" placeholder="0 to 5"> 
    <button id="check-guess"> Guess! </button> 
  </p> 
  <div id="theAnswer"> 
    <h2 id="h2">Your Reward</h2> 
  </div> 
</div>
document.getElementById("check-guess").onclick = function() {
  var randomNumber = Math.random();
  randomNumber = randomNumber * 6;
  randomNumber = Math.floor(randomNumber);
  if (document.getElementById("guess").value == randomNumber) {
    document.getElementsById("h2").innerHTML = "You got it!";
                         } else {
    document.getElementsById("h2").innerHTML = "Nope! Try Again. The number is " +  randomNumber ;
  }
} 
7
  • 2
    You need to add an id to the H2 and reference it that way. You are trying to pass a tag name instead of the id Commented Jun 12, 2019 at 15:33
  • 3
    simple typo. getElementsById Commented Jun 12, 2019 at 15:34
  • Fast spot @JasonB! Commented Jun 12, 2019 at 15:34
  • @MauroAlmeida yes Commented Jun 12, 2019 at 15:34
  • 1
    its getElementById not getElementsById Commented Jun 12, 2019 at 15:35

1 Answer 1

2

Your function getElementsById doesn't exist, it could be getElementById. The value you pass needs to be an id, not a tagname.

document.getElementById("check-guess").onclick = function() {

  var randomNumber = Math.random();

  randomNumber = randomNumber * 6;

  randomNumber = Math.floor(randomNumber);

  if (document.getElementById("guess").value == randomNumber) {

    document.getElementById("h2").innerHTML = "You got it!";

  } else {

    document.getElementById("h2").innerHTML = "Nope! Try Again. The number is " + randomNumber;
  }
}
<input id="guess">
<button id="check-guess">Check</button>
<h2 id="h2">Test</h2>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.