0

How do I get an image stored in a javascript variable, to display in an HTML code?

Say for instance, my image is stored in a variable called flowers as seen in the below javascript code:

<script>
     var flowers = "myFlowers.gif";
</script>

In the following HTML code, I reference the flowers variable in my img src in order to display the image but cant seem to get this to work.

<img src= flowers  class="card-img-top" id="flowers">

Please help, What am I doing wrong?

1
  • 2
    Unless you're using some kind of special templating language... that markup will simply instruct the browser to set the image source to literally the string flowers, not the value of the variable. Use document.getElementById('flowers').src = flowers; Commented Jan 22, 2022 at 0:28

1 Answer 1

1

You can't insert it directly like that. Instead you set the attribute src through javascript.

let flowers = "https://picsum.photos/200/300";
document.querySelector('#flowers').src = flowers;
<img  class="card-img-top" id="flowers">

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.