I’m trying to write plain JS code to implement a multiple choice question. I have been able to get the button colors to change to red or green depending on if the correct answer is selected, however I want to make sure that when a separate answer is clicked the remaining buttons revert back to their original color. I am trying to do this with a for loop. There doesn’t seem to be errors in the code as per dev tools but the red buttons just stay red when the correct answer is clicked after. Where am I going wrong here?
<!-- revert button colors (#d9edff) using the variables unclicked and doc query selector-->
document.addEventListener('DOMContentLoaded', function(){
let correct = document.querySelector(".correct_answer");
correct.addEventListener('click', function() {
correct.style.backgroundColor = 'green';
let correct_feedback = document.querySelector(".feedback");
correct_feedback.innerText = 'Correct!';
let unclicked = document.querySelectorAll(".incorrect_answer");
for (let i = 0; i < unclicked.length; i++){
unclicked.style.backgroundColor = '#d9edff';
}
});
let incorrects = document.querySelectorAll(".incorrect_answer");
incorrects.forEach(item => item.addEventListener('click', function(event) {
let clicked = event.srcElement;
clicked.style.backgroundColor = 'red';
let incorrect_feedback = document.querySelector(".feedback");
incorrect_feedback.innerText = 'Incorrect';
}));
});
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@500&display=swap" rel="stylesheet">
<link href="styles.css" rel="stylesheet">
<title>Trivia!</title>
</head>
<body>
<div class="header">
<h1>Trivia!</h1>
</div>
<div class="container">
<div class="section">
<h2>Part 1: Multiple Choice </h2>
<hr>
<h3>How many species of Dolphin are there?</h3>
<button class="correct_answer">42</button>
<button class="incorrect_answer">53</button>
<button class="incorrect_answer">24</button>
<button class="incorrect_answer">11</button>
<p class="feedback"></p>
</div>
>Solution :
let unclicked = document.querySelectorAll(".incorrects");
are you sure you want this? Not ".incorrect_answer" ?