Adding image using javascript

前端 未结 3 1456
情话喂你
情话喂你 2020-12-21 09:16

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



        
相关标签:
3条回答
  • 2020-12-21 10:11

    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";
    
    0 讨论(0)
  • 2020-12-21 10:14

    try following instead of changing innerHTML.

    function changeImage()
    {
      var parent = documeent.getElementById('x');
      parent.getElementsByTagName("img")[0].src = "newUrl";
    }
    
    0 讨论(0)
  • 2020-12-21 10:17

    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 讨论(0)
提交回复
热议问题