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.
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>
worng
document.getElementById(#adj).textContent = randomAdj;
document.getElementById(#noun).textContent = randomNoun;
use
document.getElementById("adj").innerHTML = randomAdj;
document.getElementById("noun").innerHTML = randomNoun;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.