最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Adding image using javascript - Stack Overflow

programmeradmin6浏览0评论

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

<a href="www.google" 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..

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

<a href="www.google." 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..

Share Improve this question edited May 3, 2011 at 6:30 Durga Dutt asked May 3, 2011 at 6:18 Durga DuttDurga Dutt 4,11311 gold badges35 silver badges49 bronze badges 1
  • 1 Is the missing opening < to the img tag a typo or your actual code looks like this? – Darin Dimitrov Commented May 3, 2011 at 6:20
Add a ment  | 

3 Answers 3

Reset to default 4

try this:

<a href="www.google." 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";

try following instead of changing innerHTML.

function changeImage()
{
  var parent = documeent.getElementById('x');
  parent.getElementsByTagName("img")[0].src = "newUrl";
}

As others have indicated, there are many ways to do this. The A element isn't an anchor, it's a link. And no one really uses XHTML on the web so get rid of the XML-style syntax.

If you don't have an id for the image, then consider:

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 an onload listener:

<body onload="changeImage('x', 'images/test.png');" ...>

or add a script element after the link (say just before the closing body tag) or use some other strategy for running the function after the image is in the document.

发布评论

评论列表(0)

  1. 暂无评论