3

I am trying to make a game for my two girls. It randomly selects an adjective and a noun, then displays the words for them to act out.

I can get the random words to print to the console, but now I need them to appear in the html.

Array.prototype.sample = function(){
  return this[Math.floor(Math.random()*this.length)];
}


var randomAdj = (["happy", "sad", "bouncy", "silly"].sample());
var randNoun = (["monkey", "butterfly", "puppy"].sample());

document.getElementById(#adj).textContent = randomAdj;
document.getElementById(#noun).textContent = randomNoun;

The last two lines aren't working for me (#adj and #noun are span ids used in the html).

I am only a couple of weeks into learning, so I might be missing something super obvious here.

2 Answers 2

4

The random part should work (keep in mind that modifying the prototypes is not a good practice, tho), but you have two syntax errors:

document.getElementById(#adj).textContent = randomAdj;
document.getElementById(#noun).textContent = randomNoun;

Pass "adj" and "noun" as strings:

document.getElementById("adj").textContent = randomAdj;
document.getElementById("noun").textContent = randomNoun;

You don't need the # snippet in the getElementById call. Also note that you you are using randomNoun but you declared randNoun. Here is the working code and example:

function randomItem(arr){
  return arr[Math.floor(Math.random()*arr.length)];
}


var randomAdj = randomItem(["happy", "sad", "bouncy", "silly"]);
var randomNoun = randomItem(["monkey", "butterfly", "puppy"]);

document.getElementById("adj").textContent = randomAdj;
document.getElementById("noun").textContent = randomNoun;
<span id="adj"></span>
<span id="noun"></span>

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

2 Comments

Thank you! I figured it was something little and dumb
@kristijoy81 You're welcome! Don't forget to check the answer using the button in the left side of my answer (under the vote section). Hope your girls will have fun playing it. :)
0

worng

document.getElementById(#adj).textContent = randomAdj;
document.getElementById(#noun).textContent = randomNoun;

use

document.getElementById("adj").innerHTML = randomAdj;
document.getElementById("noun").innerHTML = randomNoun;

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.