Reputation: 53
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
Reputation: 29463
With javascript:
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
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
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