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?

3
  • Leave the src empty, and then in JS, get a reference to the image using id, then simply set src to what you need. Commented Mar 6, 2020 at 9:16
  • where your variable will come from? javascript? Commented Mar 6, 2020 at 9:18
  • Does this answer your question? Programmatically change the src of an img tag Commented Mar 6, 2020 at 9:18

3 Answers 3

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" />

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

Comments

1

Get the img and set the src:

document.getElementById('image1').src='http://mywebsite.com/image.jpg';

Comments

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"

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.