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

91
Visualizações
Javascript appendChild not showing the correct image

I'm making a simple game with a background, three buttons but have run into a hiccup. The

document.body.appendChild(img);

Doesn't append the image, only shows the alt text. This is what I have so far:

<script>
    document.body.style.backgroundImage =
    "url('./back.jpg')";
    document.body.style.backgroundSize = 'contain';
    document.body.style.backgroundRepeat = 'no-repeat';
    document.body.style.backgroundPosition = 'center';
    document.body.style.backgroundSize = '100%';    

    function show_image(src, width, height, alt) {
      var img = document.createElement("img");
      img.src = src;
      img.width = width;
      img.height = height;
      img.alt = alt;
      document.body.appendChild(img);
    }

    show_image("url('./b.png')", 100,100,"btnBlue")
</script>

This is what I Get :

Result

What am I doing wrong?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are formatting your image URL like a CSS background property, the <img> element source just takes the URL itself:

show_image("url('./b.png')", 100, 100, "btnBlue") would become show_image("./b.png", 100, 100, "btnBlue")

function show_image(src, width, height, alt) {
  var img = document.createElement("img");
  img.src = src;
  img.width = width;
  img.height = height;
  img.alt = alt;
  document.body.appendChild(img);
}

show_image("https://picsum.photos/200", 100, 100, "btnBlue")

about 4 years ago · Juan Pablo Isaza 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