user15576045
user15576045

Reputation:

display image using javascript variable in html

I want to display an image on screen, but define the link to the image in my js script, like so:

 <script>
    function myFunction() {
    var imgUrl = "https://www.linkpicture.com/q/IMG_4902"
    var modelName = "Model Name"
    document.getElementById("myText").innerHTML = modelName;
    
    }
    </script>
<body onload="myFunction()">
<div class="image-area">
        <div class="img-wrapper">
            <img src="" id="myImg" alt="">

so in the img src, I want to display the image based on the imgUrl content in my script. How is this possible?

Upvotes: 1

Views: 3643

Answers (3)

0xjustuzair
0xjustuzair

Reputation: 587

You can do something like this

let myImg=document.querySelector('#myImg');
let imgUrl = "https://www.linkpicture.com/q/IMG_4902";
myImg.src=imgUrl

Upvotes: 1

Spectric
Spectric

Reputation: 31987

You can modify the source of the image by assigning a new value to the src property.

<script>
  function myFunction() {
    var imgUrl = "https://www.gravatar.com/avatar/0fdacb141bca7fa57c392b5f03872176?s=48&d=identicon&r=PG&f=1"
    var modelName = "Model Name"
    //   document.getElementById("myText").innerHTML = modelName;
    document.getElementById("myImg").src = imgUrl;
  }
</script>

<body onload="myFunction()">
  <div class="image-area">
    <div class="img-wrapper">
      <img src="" id="myImg" alt="">
    </div>
  </div>
</body>

Upvotes: 2

vanowm
vanowm

Reputation: 10201

Very strange question...this doesn't work for some reason?

document.getElemetnById("myImg").src = imgUrl;

Upvotes: 1

Related Questions