William William - 24 days ago 7
Javascript Question

Storing the Text inside a Span

I need help for a web development project in high school, we're still doing very elementary stuff & my teacher checks our code, so no extremely advanced answers please.

I have a bunch of empty spans with

id
s like
guess1
,
guess2
,
guess3
and so on. I'm trying to store user inputs (playerGuess) in the innerHTML of the next empty one every time they enter their input, but I really don't get how to. I tried doing something like

"guess" + guessnumber.innerHTML = playerGuess


or something like

test = "guess" + guessnumber

test.innerHTML = playerGuess


I understand why neither are working, so how do I properly format it? thanks

Answer

Here's a span:

<span id="guess1"></span>

You can get the guess with:

playerGuess = window.prompt("Guess: ");

Or from an input, like so:

playerGuess = document.getElementById("guess-input").value;

There is probably a loop to keep track of how many guesses are made:

var i = 0;
while (i < MAX_TRIES && playerGuess !== target) {
    playerGuess = prompt("Guess: ");
    i++;
}

And you need to put the guess in the span with:

document.getElementById("guess"+i).textContent = playerGuess;

These are the pieces. You can do it.

Be sure to declare all your variables with var and initialize any constants.

Comments