When I loop through individual elements during their creation I am able to use them and add them to the HTML page, but when I add them to an array it doesn't function well anymore, in fact I am unable to fetch any of the elements I've added to the array at all.
const questions = fetchQuestions();
function fetchQuestions() {
const url = 'https://opentdb.com/api.php?amount=10&type=multiple';
let questions = []; // HTML array
fetch(url)
.then(function (response) {
return response.json();
})
.then(function (json) {
let results = json.results;
for (let i = 0; i < results.length; i++) {
// container part
let div = document.createElement('div');
div.id = 'question-' + i;
let fieldset = document.createElement('fieldset');
div.appendChild(fieldset);
// set question number
let legend = document.createElement('legend');
legend.innerHTML = 'Question ' + i;
fieldset.appendChild(legend);
// set question text
let question = document.createElement('p');
question.innerHTML = results[i].question;
fieldset.appendChild(question);
// set question options
let answerContainer = document.createElement('p');
let answers = [];
answers.push(createRadioButton('answer-' + i, results[i].correct_answer, 'answer-' + i + '-correct'));
answers.push(createRadioButton('answer-' + i, results[i].incorrect_answers[0]));
answers.push(createRadioButton('answer-' + i, results[i].incorrect_answers[1]));
answers.push(createRadioButton('answer-' + i, results[i].incorrect_answers[2]));
shuffle(answers);
answers.forEach(element => {
answerContainer.appendChild(element);
});
fieldset.appendChild(answerContainer);
questions.push(div);
}
});
console.log(questions);
console.log(questions[0]);
console.log(questions.length);
return questions;
}
function createRadioButton(name, text, id = false) {
let label = document.createElement('label');
let radio = document.createElement('input');
radio.setAttribute('type', 'radio');
radio.setAttribute('name', name);
if (id) radio.setAttribute('id', id);
label.append(radio, text);
return label;
}
function shuffle(array) {
array.sort(() => Math.random() - 0.5);
}
I first tried using promises and then I was getting a [Object promise] and could access elements, but could not use appendChild(array[0])
it would throw an error stating that what I'm trying to add isn't an array. How can I overcome this issue and access the elements so that I may be able to add them into my HTML?