Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 889
kristijoy81 Avatar asked Jun 07 '26 18:06

kristijoy81


1 Answers

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>
like image 90
Ionică Bizău Avatar answered Jun 10 '26 07:06

Ionică Bizău



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!