KrisGeor
KrisGeor

Reputation: 53

How do I put a variable in an src attribute?

Ok so I have this problem . I want to put the myPath variable into my src attribute of my image.

var myPath = img/image.png;
//it's actually set by another function

document.getElementById("myDiv").innerHTML = "<img src='myPath'>";

But it doesn't seem to work. How do I do it ?

(I'm really new with js)

Upvotes: 1

Views: 9335

Answers (3)

Rounin
Rounin

Reputation: 29463

With javascript:

  • you can add and remove elements to and from documents; and
  • you can add and remove attributes to and from elements

So if in your markup you have something like:

<div id="my-div"></div>

You can add an img element as a child of the div element, like so:

var myDiv = document.getElementById('my-div'); // grabs #my-div
var myPath = 'img/image.png'; // initialises string variable myPath
var myImg = document.createElement('img'); // creates a new img element


myImg.setAttribute('src', myPath); // adds a src attribute (with the value myPath) to myImg
myDiv.appendChild(myImg); // adds a child element (myImg) to myDiv

Upvotes: 3

Frankusky
Frankusky

Reputation: 1083

Just concat it as an string

var myPath = "img/image.png";
//it's actually set by another function

document.getElementById("myDiv").innerHTML = "<img src='"+myPath"'>";

Upvotes: 1

Dij
Dij

Reputation: 9808

myPath already contains a string, in your code you are not using the variable myPath rather myPath is just a part of string literal, you need to use string concatenation, you can do something like this:

var myPath = "img/image.png";
//it's actually set by another function

document.getElementById("myDiv").innerHTML = "<img src='" + myPath + "'>";

Upvotes: 2

Related Questions