I'm trying to display different images based on a json question id using vanilla javascript and the document.createElement() method. This code will display no images, but if I only try to display one image it will work. Here is the pertainent code:
let img = document.createElement("img");
img.src = 'images/image1'
if (questions.id === 0) {
questionImageElement.appendChild(img)
}
let img2 = document.createElement('img')
img2.src = "images/image2"
if(questions.id === 1) {
questionImageElement.appendChild(img2)
}
let img3 = document.createElement('img')
img3.src = "images/image3"
if(questions.id === 2) {
questionImageElement.appendChild(img3)
}
let img4 = document.createElement('img')
img4.src = "images/image4.png"
if(questions.id === 3) {
questionImageElement.appendChild(img4)
} else {
questionImageElement.innerText = " "
}
sample json question
{
id: 0,
question: ' 1. How many possible values are there for a boolean variable?',
answers: [
{text: '1', correct: false},
{text: '2', correct: true},
{text: '3', correct: false},
{text: 'There is an infinite number of possibilities', correct: false}
]
},
If I only have only one document.createElement() method, the image will display. This way with multiple createElement() methods, it won't work. I have tried using an array of nodes and entering the array index into the appendChild method e.g. appendChild(img[0])
but that won't work either. How can this be accomplished?
CodePudding user response:
Remove the last else statement. The last else statement that you have is clearing all of the images from the DOM if the id is not equal to 3. In this case, your id is 0, so what is probably happening is that the images are being added, but then cleared by that else statement.