I am making a small quiz application using javascript and html. The quiz is set up so that the user can only see one question on the page. When they press the previous and next buttons, it shows the user the previous and next question respectively.
What I am trying to do is, loop through an array of elements returned by getElementByClassName and display the next item each time the user presses the "next" button. The problem that I currently have is, when the "next" button is pressed, every single element that comes after the first one is displayed onto the page. There is also a "previous" button on the page that shows the user the immediate previous element, however it removes the very first element in the array, shows an "Cannot set property 'display' of undefined" error and the rest of the div elements are still shown on the page.
This is the current code
HTML:
const nextBtn = document.getElementById('next');
const prevBtn = document.getElementById('prev');
const quizes = document.getElementsByClassName('quiz');
//show and hide divs when user presses next
nextBtn.addEventListener('click', function() {
for (i = 0; i < quizes.length; i++) {
quizes[i].style.display = "block";
}
})
prevBtn.addEventListener('click', function() {
if (quizes.length > 1) {
for (i = 0; quizes.length > 1; i--) {
if (quizes[i].display = "block") {
quizes[i].style.display = "none";
}
}
} else {
alert('no more previous questions!')
}
})
<div class="quiz">
<p>Question 1</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
<div class="quiz" style="display: none">
<p>Question 2</p>
<input type="radio" name="answer" value="1">
<input type="radio" name="answer" value="2">
<input type="radio" name="answer" value="3">
</div>
<button id="prev">Prev</button>
<button id="next">Next</button>
question from:
https://stackoverflow.com/questions/66065465/loop-through-an-array-of-divs-and-only-show-one-each-time-using-javascript 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…