Ive made a quiz app, with HTML and JS only and im trying to remove an id from a element which has the attribute, however when i run the code to remove it my JS doesnt find the attribute in any of the elements, if i manually inspect i can see it in the html?
i do add this element in the JS above it, could this be because the DOM hasnt updated?
choices.forEach(choice => { choice.addEventListener('click', e => { if(!acceptingAnswers) return; acceptingAnswers = false; const selectedChoice = e.target; const selectedAnswer = selectedChoice.dataset["number"]; const classToApply = selectedAnswer == currentQuestion.answer ? 'correct' : 'incorrect'; selectedChoice.parentElement.classList.add(classToApply); if (classToApply === 'correct'){ incrementScore(CORRECT_BONUS); } else{ for(let i = 0; i<currentChoices.length; i++){ if(currentChoices[i].dataset["number"] != currentQuestion.answer) continue; currentChoices[i].parentElement.classList.add("correct"); currentChoices[i].id = "correctAnswer"; } } correctAnswer = document.getElementById("correctAnswer"); setTimeout(() =>{ selectedChoice.parentElement.classList.remove(classToApply); if(correctAnswer){ correctAnswer.parentElement.classList.remove("correct"); for (choice of document.querySelectorAll(".choice-text")) { if (choice.hasAttribute("correctAnswer")){ choice.getAttribute("correctAnswer"); choice.removeAttribute("correctAnswer"); console.log("Removed") } } } getNewQuestion(); }, 1000);
Advertisement
Answer
I have changed some things around and used a class instead of id which seems to work much better.
choices.forEach(choice => { choice.addEventListener('click', e => { if(!acceptingAnswers) return; acceptingAnswers = false; const selectedChoice = e.target; const selectedAnswer = selectedChoice.dataset["number"]; const classToApply = selectedAnswer == currentQuestion.answer ? 'correct' : 'incorrect'; selectedChoice.parentElement.classList.add(classToApply); if (classToApply === 'correct'){ incrementScore(CORRECT_BONUS); } else{ for(let i = 0; i<currentChoices.length; i++){ if(currentChoices[i].dataset["number"] != currentQuestion.answer) continue; currentChoices[i].parentElement.classList.add("correct"); currentChoices[i].classList.add("correctAnswer"); } } correctAnswer = document.querySelector(".correctAnswer"); setTimeout(() =>{ selectedChoice.parentElement.classList.remove(classToApply); if(correctAnswer){ correctAnswer.parentElement.classList.remove("correct"); for (choice of document.querySelectorAll(".choice-text")) { if (choice.classList.contains("correctAnswer")){ choice.classList.remove("correctAnswer"); } } } getNewQuestion(); }, 1000);