Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

140
Views
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')
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?

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!