0

I am trying to add an image into HTML. Using the following works:

<img id="image1" src="http://image.jpg" alt=" " width="300" height="300" />

All i want to do is replace the http with a variable so I can call in the website rather than have it be physically inline:

<img id="image1" src=URL alt=" " width="300" height="300" />

Can anyone help?

Mahatmasamatman
  • 1,537
  • 2
  • 6
  • 20
  • Leave the src empty, and then in JS, get a reference to the image using `id`, then simply set `src` to what you need. – Teemu Mar 06 '20 at 09:16
  • where your variable will come from? javascript? – as-if-i-code Mar 06 '20 at 09:18
  • Does this answer your question? [Programmatically change the src of an img tag](https://stackoverflow.com/questions/11722400/programmatically-change-the-src-of-an-img-tag) – Stephane Vanraes Mar 06 '20 at 09:18

3 Answers3

1

Get the img and set the src:

document.getElementById('image1').src='http://mywebsite.com/image.jpg';
as-if-i-code
  • 2,103
  • 1
  • 10
  • 19
Adder
  • 5,708
  • 1
  • 28
  • 56
1

You want to dynamically change your src attribute, here is how to do it :

// we selct the element to change in a variable
var el = document.getElementById("image1");

// we define a new image
var new_url = 'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcT744-ntmnfTx78ZjYUG9t_SkW-M2JmpJaUr6iYlyhaVzkXT9q2';

// we set the new image
el.setAttribute("src",new_url);
<img id="image1" src="http://image.jpg" alt="nothing to show" width="300" height="300" />
iliasse
  • 247
  • 1
  • 7
0

In your html don't set the image source, but still have the img element in the DOM. I.e:

<img id="image1" alt=" " width="300" height="300" />

In your javascript (which should be loaded in the bottom of your <body> tag in your html) you do as follows:

var img1 = document.getElementById('image1');

img1.src = "/some/url/or/file-path/here.jpg"
IncrediblePony
  • 645
  • 9
  • 31