Home > front end >  how to add image to html, but the url is stored in js variable
how to add image to html, but the url is stored in js variable

Time:11-10

i have a api which generates random json details of image, i am trying to make a website which show different images every time u press a button.

something like this one:

<html>
 <head>
    <title>zzz</title>
 </head>
 <body>

<div id="img_home"></div>
<button onclick="addimage()">next</button>

<script>
function addimage() {
    var img = new Image();
    img.src = "https://www.abcd.com/image-generator.json"
    img_home.appendChild(img);
}
</script>
</body>

CodePudding user response:

Try This

function addimage() {
var img = new Image();
img.src = "https://www.abcd.com/image-generator.json";
const imgTag = document.createElement("img");
imgTag.setAttribute("src", img.src);
document.div.appendChild(imgTag );
}

CodePudding user response:

function addimage() {
    var imgSrc = "https://www.abcd.com/image-generator.json";
    const imgTag = document.createElement("img");
    imgTag.setAttribute("src", imgSrc);
    document.getElementById("img_home").appendChild(imgTag);
}
  • Related