Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

145
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda