Adding an image using javascript
I have an html page that has an image in the anchor tag code:
<a href="www.google.com" id="x"><img src="images/test.png" /></a>
on body onload event I call a javascript function that dynamically changes the image. My code is:
<script type="text/javascript">
function changeImage()
{
document.getElementById('x').innerHTML= '<img src="images/test2.png" />';
}
</script>
This works fine in firefox, but doesn't work in google chrome, etc. Please, help..
+3
3 answers
try the following:
<a href="www.google.com" id="x"><img id="y" src="images/test.png" /></a>
in js
function changingImg(){
document.getElementById("y").src="./images/test2.png"
}
Tested in Chrome and IE.
Then try the following: [hopes the identifier <a>is accessible and has at least one img tag]
var x = document.getElementById("x");
var imgs = x.getElementsByTagName("img");
imgs[0].src="./images/img02.jpg";
+4
, . A , . XHTML , XML-.
, :
function changeImage(id, src) {
var image;
var el = document.getElementById(id);
if (el) {
image = el.getElementsByTagName('img')[0];
if (image) {
image.src = src;
}
}
}
Then you can use the onload listener:
<body onload="changeImage('x', 'images/test.png');" ...>
either add a script element after the link (say, before the closing body tag) or use a different strategy to run the function after the image is in the document.
0