I’m trying to use a function that appends a text onto an answer choice on a multiple choice quiz but I can only seem to access the first answer value.
<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>name</title>
</head>
<h1>
name
</h1>
<body style="background-color:rgb(73, 88, 83);">
<div id="question1">
<p>1. which planet is considered earth's sister planet?</p>
<a href = "#">
<p id = "answer" value = "wrong">a. moon</p>
</a>
<a href = "#">
<p id = "answer" value = "correct">b. venus</p>
</a>
<a href = "#">
<p id = "answer" value = "wrong">c. mars</p>
</a>
</div>
<div id="question2">
<p>2. when did apollo 11 land?</p>
<a href = "#">
<p id = "answer" value = "correct">a. 1969</p>
</a>
<a href = "#">
<p id = "answer" value = "wrong">b. 1970</p>
</a>
<a href = "#">
<p id = "answer" value = "wrong">c. 1968</p>
</a>
</div>
<div id="question3">
<p>3. which is the planet mars?</p>
<a href = "#">
<p id = "answer" value = "wrong">a. <img src = "https://upload.wikimedia.org/wikipedia/commons/e/e1/FullMoon2010.jpg" width="50" height="50"> </p>
</a>
<a href = "#">
<p id = "answer" value = "wrong">b. <img src = "https://upload.wikimedia.org/wikipedia/commons/0/0d/Africa_and_Europe_from_a_Million_Miles_Away.png" width="50" height="50"> </p>
</a>
<a href = "#">
<p id = "answer" value = "correct">c. <img src = "https://upload.wikimedia.org/wikipedia/commons/0/02/OSIRIS_Mars_true_color.jpg" width="50" height="50"> </p>
</a>
</div>
<div class="buttons">
<button id="reset-button"> Reset </button>
</div>
<script>
const reset = document.getElementById("reset-button")
var clicked = document.getElementById("answer")
var text = document.createTextNode(" correct")
var text_2 = document.createTextNode(" wrong")
reset.addEventListener('click', resetquestions)
clicked.addEventListener('click', giveAnswer)
function giveAnswer() {
if(clicked.value === "correct") {
clicked.appendChild(text)
}
else {
clicked.appendChild(text_2)
}
}
function resetquestions() {
if(clicked.value === "correct") {
text.remove()
}
else {
text_2.remove()
}
}
</script>
</body>
</html>
I want to be able to append a correct or wrong text to every answer choice that I click. I tried changing the ID’s to answer_1_1, answer_1_2 and adding an event listener to them individually but unfortunately I wasn’t even able to get the first response’s answer anymore. How can I fix this? sidenote: i’m not allowed to use buttons or input for the answer choices.
2
Answers
As in the comments on your question Id’s are unique, so using the same id for different elements will not work. You can use classnames for this use case. Here is some code to add all event listeners to the same DOM elements when using classnames instead of ID’s:
Example of using classname on a element:
The use of values on a
<p>
element is not ideal, instead u could use radiobuttonsIDs have to be unique.
I have made a few updates to your code to simplify and solve your problems.