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 >
<div ></div>
<h2 >/h2>
<p ></p>
<p ></p>
<p ></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 >${movie.imgFile}
<h2 >${movie.name}</h2>
<p >${movie.releaseYear}</p>
<p >${movie.runtime}</p>
<p >${movie.cast} </p>
</div>
`
</script>
</body>
</html>
Why does it not work this way?
CodePudding user response:
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 >${movie.imgFile}
, aside from not having a close tag for your </div>
, should be written as follows
<div >
<img src="${movie.imgFile}" />
</div>
or in a single line if you prefer
<div ><img src="${movie.imgFile}" /></div>
CodePudding user response:
add folder path if full path of the file is not stored with movie.imgFile.