Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

142
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda