Никак не могу понять, почему оно не работает.
const questions = [
{
question: "Question1?",
answers: [
{
text: "a",
correct: false
},
{
text: "b",
correct: false
},
{
text: "c",
correct: true
},
{
text: "d",
correct: false
},
]
},
{
question: "Question2?",
answers: [
{
text: "q",
correct: false
},
{
text: "w",
correct: false
},
{
text: "e",
correct: false
},
{
text: "r",
correct: true
},
]
}
];
const questionElement = document.getElementById("question");
const answerButtons = document.getElementById("answer-buttons");
const nextButton = document.getElementById("next-btn");
let currentQuestionIndex = 0;
let score = 0;
function startQuiz() {
currentQuestionIndex = 0;
score = 0;
nextButton.innerHTML = "Next";
showQuestion();
}
function showQuestion() {
let currentQuestion = questions[currentQuestionIndex];
let questionNo = currentQuestionIndex + 1;
questionElement.innerHTML = questionNo + ". " + currentQuestion.question;
currentQuestion.answers.forEach(answer => {
const button = document.createElement("button");
button.innerHTML = answer.text;
button.classList.add("btn");
answerButtons.appendChild(button);
});
}
startQuiz();
*{
margin: 0;
padding: 0;
box-sizing: 0;
}
body{
background: #001e4d;
}
.app{
background: #fff;
width: 90%;
max-width: 600px;
margin: 100px auto 0;
border-radius: 10px;
padding: 30px;
}
.app h1{
font-weight: 25px;
color: #001e4d;
font-weight: 600;
border-bottom: 1px solid #333;
padding-bottom: 30px;
}
.quiz{
padding: 20px 0;
}
.quiz h2{
font-size: 18px;
color: #001e4d;
font-weight: 600;
}
.btn{
background: #fff;
color: #222;
font-weight: 500;
width: 100%;
border: 1px solid #222;
padding: 10px;
margin: 10px 0;
text-align: left;
border-radius: 4px;
cursor: pointer;
transition: all .3s;
}
.btn:hover:not([disabled]){
background: #222;
color: #fff;
}
.btn:disabled{
cursor: no-drop;
}
#next-btn{
background: #001e4d;
color: #fff;
font-weight: 500;
width: 150px;
border: 0;
padding: 10px;
margin: 20px auto 0;
border-radius: 4px;
cursor: pointer;
display: none;
}
.correct{
background: #9aeabc;
}
.incorrect{
background: #ff9393;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Quiz</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="app">
<h1>Задачи</h1>
<div class="quiz">
<h2 id="question">Вопрос</h2>
<div class="answer-buttons">
<button class="btn">Ответ1</button>
<button class="btn">Ответ2</button>
<button class="btn">Ответ3</button>
<button class="btn">Ответ4</button>
</div>
<button id="next-btn">Next</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Выдает ошибку:
Uncaught TypeError: Cannot read properties of null (reading 'appendChild')
getElementById("answer-buttons")
, однако такого элемента с id='answer-buttons' у вас нет