I've looked at many other posts and I think I'm using the exact syntax suggested. However, I'm not getting the images to show up. I have a jsfiddle. Is it a jsfiddle issue? It's also not working on a website I'm working on.
<div id="divtest">Hello</div>
<img id="imgtest" />
<img id="imgreal" src=".jpeg" />
var string = "url('.jpeg')";
alert(string)
document.getElementByID("divtest").style.backgroundImage = string;
document.getElementByID("imgtest").src = string;
I've looked at many other posts and I think I'm using the exact syntax suggested. However, I'm not getting the images to show up. I have a jsfiddle. Is it a jsfiddle issue? It's also not working on a website I'm working on.
<div id="divtest">Hello</div>
<img id="imgtest" />
<img id="imgreal" src="http://www.premiumbeat.com/blog/wpcontent/uploads/2012/12/free.jpeg" />
var string = "url('http://www.premiumbeat.com/blog/wpcontent/uploads/2012/12/free.jpeg')";
alert(string)
document.getElementByID("divtest").style.backgroundImage = string;
document.getElementByID("imgtest").src = string;
Share
Improve this question
asked Nov 18, 2013 at 18:53
abalterabalter
10.4k18 gold badges98 silver badges166 bronze badges
2
|
2 Answers
Reset to default 10Two minor problems:
getElementByID
is not a function;getElementById
is.The format for a url is different for an image source and a background image. Try this:
var string = 'http://www.premiumbeat.com/blog/wp-content/uploads/2012/12/free.jpeg'; document.getElementById("divtest").style.backgroundImage = "url('" + string + "')"; document.getElementById("imgtest").src = string;
Replace getElementByID
by getElementById
and there is another error in your code:
you write:
var string = "url('http://www.premiumbeat.com/blog/wp-content/uploads/2012/12/free.jpeg')";
document.getElementById("imgtest").src = string;
But src
doesn't need url(
, so you should write :
var str1 = "url('http://www.premiumbeat.com/blog/wp-content/uploads/2012/12/free.jpeg')";
document.getElementById("divtest").style.backgroundImage = str1 ;
var str2 = 'http://www.premiumbeat.com/blog/wp-content/uploads/2012/12/free.jpeg';
document.getElementById("imgtest").src = str2;
Hope this helps
document.getElementByID
!==document.getElementById
. – Teemu Commented Nov 18, 2013 at 18:58