I’m trying to display an image in a div in html. I used fetch to get the json data from the api : https://collectionapi.metmuseum.org/public/collection/v1/objects/435828. The response gives json date with the image url named "primaryImage". I’m able to display it in text but not as an image.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Image</title>
</head>
<body>
<img id="test">
<script>
let getimage = document.getElementbyId('test');
getimage.src= "data"
fetch('https://collectionapi.metmuseum.org/public/collection/v1/objects/435828')
.then((response) => response.json())
.then((data) => texting.innerText = data.primaryImage);
</script>
</body>
</html>
2
Answers
For your sample page,
replace;
line with;
The process is fairly simple and can be described as follows:
image
in a variable so that you can access it later.API
.JSON
.image
source, or specifically thesrc
attribute, as theAPI
response’sprimaryImage
field.Here’s a live demo to illustrate:
You might as well think of adding a loading text or spinner while the image loads but am not going into that as it’ll make my answer out of scope.