Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding image using javascript

Tags:

javascript

I have a html page in which there is an image in anchor tag code is :

<a href="www.google.com" id="x"><img src="images/test.png" /></a>

on body onload event i am calling a javascript function which dynamically changes the image . My code is:

<script type="text/javascript">
function changeImage()
{
  document.getElementById('x').innerHTML= '<img src="images/test2.png" />'; 
}
</script>

This is working fine in firefox but not working in google chrome and ie. Please help..

like image 728
Durga Dutt Avatar asked May 25 '26 21:05

Durga Dutt


2 Answers

try this:

<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 this: [hoping that id of <a> is available and have at least one img tag]

var x = document.getElementById("x");
var imgs = x.getElementsByTagName("img");
imgs[0].src="./images/img02.jpg";
like image 90
Harry Joy Avatar answered May 31 '26 14:05

Harry Joy


try following instead of changing innerHTML.

function changeImage()
{
  var parent = documeent.getElementById('x');
  parent.getElementsByTagName("img")[0].src = "newUrl";
}
like image 26
Anil Namde Avatar answered May 31 '26 13:05

Anil Namde



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!