I am new to javascript and am working on a quiz project. I am trying to loop through the divs so that they show up one by one on the click of the next button. For some reason it skips the second div.
<div id='question-one' class='questions active-question'></div>
<div id='question-two' class='questions active-question'></div>
<div id='question-three' class='questions active-question'></div>
const nextButton = document.getElementById('myButton');
nextButton.addEventListener('click', setNextQuestion);
function setNextQuestion() {
var isNowTheActiveQuestion = document.getElementsByClassName('questions');
for (activeQuestion of isNowTheActiveQuestion) {
activeQuestion.classList.remove('active-question');
}
activeQuestion.classList.add('active-question');
}
You don't need to give "active-question" class for all items. You should give just what item you want to see first.
<div id='question-one' class='questions active-question'></div>
<div id='question-two' class='questions'></div>
<div id='question-three' class='questions'></div>
Now come to the Js code
const nextButton = document.getElementById('myButton');
nextButton.addEventListener('click', setNextQuestion);
let count = 1;
function setNextQuestion() {
const isNowTheActiveQuestion = document.getElementsByClassName('questions');
for(let i = 0; i < isNowTheActiveQuestion.length; i++){
isNowTheActiveQuestion[i].classList.remove('active-question');
};
if(count > isNowTheActiveQuestion.length - 1){
count = 0;
};
isNowTheActiveQuestion[count++].classList.add('active-question');
};