kristijoy81
kristijoy81

Reputation: 33

Select random item from array

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.

Upvotes: 3

Views: 129

Answers (2)

Sandeep
Sandeep

Reputation: 1479

worng

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

use

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

Upvotes: 0

Ionică Bizău
Ionică Bizău

Reputation: 113365

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>

Upvotes: 4

Related Questions