When I use this code it returns "4. numbers". How can I get the first item which is "1. strings" ?
const qOption1 = document.querySelector('.questionsOption1')
const questions = [{
questionText: "Commonly used data types DO NOT include:",
options: ["1. strings", "2. booleans", "3. alerts", "4. numbers"],
answer: "3. alerts",
}
for (let op of questions[0].options) {
qOption1.innerHTML = op;
}
2
Answers
4. numbers
is the value of the last data arrayQuestion is a bit unclear, however I will try and give some answers.
Right now you are getting all the options, in a loop, and each iteration of the loop is overwriting the questionsOption1-element. Giving you the last item, once loop is done.
Get first item in options array:
If you simply want the first element from the
options
array of the first object in thequestions
array and set it to thequestionsOption1
-element it is very simple:As you can see, no loops needed.
You can also remove the first item from the array:
Get all option from first question:
If you however want all the options for the first question then you would need to loop.
Note: Changed elements class from
questionsOption1
toquestionsOptions
.Get all questions and all options: