Skip to content
Advertisement

Get image from object and display on HTML

I want to get an image from an object in JavaScript and display it via HTML.

The text parts are working fine, like the movie name etc., but I cannot see my image. The only thing I see is black_adam.jpg as text. The image is in the same folder as my index.html. I tried to add a slash in front of imgFile: "/black_adam.jpg".

This is my code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>Document</title>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="" />
    <meta name="keywords" content="" />
    <meta name="author" content="" />
    <!-- FAVICON -->
    <link rel="icon" type="image/png" sizes="32x32" href="#" />
    <!-- FONTS -->

    <!-- ICON LIBRARY -->

    <!-- PROJECT STYLES -->
    <!-- <link rel="stylesheet" href="style.css"> -->

    <style>
      .movie {
        width: 200px;
        height: 300px;
        background-color: black;
        color: #fff;
      }
    </style>

  </head>
  <body style="font-family: 'Segoe UI', sans-serif">
    <div class="movie">
      <div class="img"></div>
      <h2 class="movie-title">/h2>
      <p class="release"></p>
      <p class="duur"></p>
      <p class="cast"></p>
    </div>

    <script>
      const movieEl = document.querySelector(".movie");

      const movie = {
        id: 1,
        name: "Black Adam",
        description:
          "Nearly 5,000 years after he was bestowed with the almighty powers of the Egyptian gods-and imprisoned just as quickly-Black Adam (Johnson) is freed from his earthly tomb, ready to unleash his unique form of justice on the modern world.",
        releaseYear: 2022,
        runtime: "2 hr 4 min",
        rating: 6.9,
        cast: ["Dwayne Johnson", " Aldis, Hodge", " Pierce Brosnan"],
        imgFile: "black_adam.jpg"
      };
      
      movieEl.innerHTML =
      `
      <div class="img">${movie.imgFile}
        <h2 class="movie-title">${movie.name}</h2>
        <p class="release">${movie.releaseYear}</p>
        <p class="duur">${movie.runtime}</p>
        <p class="cast">${movie.cast} </p>
      </div>
      `
    </script>
  </body>
</html>

Why does it not work this way?

Advertisement

Answer

The reason you’re seeing your file name as text is that you’ve done nothing to display the image as an image in your HTML

The line <div class="img">${movie.imgFile}, aside from not having a close tag for your </div>, should be written as follows

<div class="img">
    <img src="${movie.imgFile}" />
</div>

or in a single line if you prefer

<div class="img"><img src="${movie.imgFile}" /></div>
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement