I need to a get a random string from the objects inside an array when you click the button. But for some reason my code is not executing.
var quotes = [{
quote: "Quote1",
source: "Source1"
},
{
quote: "Quote2",
source: "Source2"
},
{
quote: "Quote3",
source: "Source3"
},
{
quote: "Quote4",
source: "Source4"
},
{
quote: "Quote5",
source: "Source5"
}
];
function getRandomquote() {
var randomindex = Math.floor(Math.random() * (quotes.length));
var quotesarr = quotes[randomindex];
var objquote = quotesarr.quote;
var objsource = quotesarr.source;
document.getElementById("quote").innerHTML = objquote;
document.getElementById("source").innerHTML = objsource;
}
function printQuote() {
document.getElementById("loadQuote").onclick = getRandomquote;
}
printQuote();
<div class="container">
<div id="quote-box">
<p class="quote"> hello</p>
<p class="source"> hello</p>
</div>
<button id="loadQuote" onclick="printQuote();">Show another quote</button>
I am getting this error message:
Uncaught TypeError: Cannot set property 'innerHTML' of null at HTMLButtonElement.getRandomquote (randomtest1.js:27)
Update after answers below
I changed getElementById to getElementsByClassName, and now there are no error messages.
But when I click the button, it does not change the elements. I believe I have made a mistake on the printQuote function. I cannot figure it out.