Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Cannot display different images created using document.createElement

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')
img3.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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading