Quote machine: for loop don't work

html:

button id="new-quote" onclick="newQuote()"> New "Quote" js: quotes= [{quote:...,author:...},{quote:...,author:......}] function newQuote(){ for (let i = 0 ; i < quotes.length ; i++){ counter = quotes[i].quote; document.getElementById("text").innerHTML = counter; } } it don't iterate over each quote onclick, it shows only the quote n#9

It’s been a while, but innerHTML overwrites the contents. So it is iterating over each one, it’s just doing it so fast that you only see the last one. Perhaps try append.

1 Like

if this is for the random quote generator why use a for loop that always ends at quotes.length (ie the last quote)? You only need to display 1 quote, picked at random from your array…

ty, i did that and finished the task already , https://codepen.io/ahmed-derbel/pen/QzRyPb , the problem is repeating the same quote onclick sometimes , those projects are for learning after all so i just wanted to try for loop for the project to iterate over each quote when i click , but i failed .

log the index of the last quote - if the random number for the new quote = that number (+1 as we count from 0) redo the random number (a “WHILE new number = current number” loop if you set new number = current number before entering the loop should work

1 Like