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?
JavaScript
x
45
45
1
choices.forEach(choice => {
2
choice.addEventListener('click', e => {
3
if(!acceptingAnswers) return;
4
5
acceptingAnswers = false;
6
const selectedChoice = e.target;
7
const selectedAnswer = selectedChoice.dataset["number"];
8
9
const classToApply = selectedAnswer == currentQuestion.answer ? 'correct' : 'incorrect';
10
11
12
selectedChoice.parentElement.classList.add(classToApply);
13
14
if (classToApply === 'correct'){
15
incrementScore(CORRECT_BONUS);
16
} else{
17
for(let i = 0; i<currentChoices.length; i++){
18
if(currentChoices[i].dataset["number"] != currentQuestion.answer) continue;
19
20
currentChoices[i].parentElement.classList.add("correct");
21
currentChoices[i].id = "correctAnswer";
22
23
}
24
}
25
26
correctAnswer = document.getElementById("correctAnswer");
27
28
29
setTimeout(() =>{
30
selectedChoice.parentElement.classList.remove(classToApply);
31
if(correctAnswer){
32
correctAnswer.parentElement.classList.remove("correct");
33
for (choice of document.querySelectorAll(".choice-text")) {
34
if (choice.hasAttribute("correctAnswer")){
35
choice.getAttribute("correctAnswer");
36
choice.removeAttribute("correctAnswer");
37
console.log("Removed")
38
}
39
}
40
41
}
42
getNewQuestion();
43
44
}, 1000);
45
Advertisement
Answer
I have changed some things around and used a class instead of id which seems to work much better.
JavaScript
1
42
42
1
choices.forEach(choice => {
2
choice.addEventListener('click', e => {
3
if(!acceptingAnswers) return;
4
5
acceptingAnswers = false;
6
const selectedChoice = e.target;
7
const selectedAnswer = selectedChoice.dataset["number"];
8
9
const classToApply = selectedAnswer == currentQuestion.answer ? 'correct' : 'incorrect';
10
11
12
selectedChoice.parentElement.classList.add(classToApply);
13
14
if (classToApply === 'correct'){
15
incrementScore(CORRECT_BONUS);
16
} else{
17
for(let i = 0; i<currentChoices.length; i++){
18
if(currentChoices[i].dataset["number"] != currentQuestion.answer) continue;
19
20
currentChoices[i].parentElement.classList.add("correct");
21
currentChoices[i].classList.add("correctAnswer");
22
23
}
24
}
25
26
correctAnswer = document.querySelector(".correctAnswer");
27
28
29
setTimeout(() =>{
30
selectedChoice.parentElement.classList.remove(classToApply);
31
if(correctAnswer){
32
correctAnswer.parentElement.classList.remove("correct");
33
for (choice of document.querySelectorAll(".choice-text")) {
34
if (choice.classList.contains("correctAnswer")){
35
choice.classList.remove("correctAnswer");
36
}
37
}
38
}
39
getNewQuestion();
40
41
}, 1000);
42