Caz Meechan
Caz Meechan

Reputation: 3

Generating HTML with strings

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?

Upvotes: 0

Views: 70

Answers (3)

Adder
Adder

Reputation: 5868

Get the img and set the src:

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

Upvotes: 1

iliasse
iliasse

Reputation: 257

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

Upvotes: 1

IncrediblePony
IncrediblePony

Reputation: 752

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"

Upvotes: 0

Related Questions