Adding an img element to a div with javascript

后端 未结 4 1544
囚心锁ツ
囚心锁ツ 2020-11-29 02:54

I am trying to add an img to the placehere div using JavaScript, however I am having no luck. Can anyone give me a hand with my code?



        
相关标签:
4条回答
  • 2020-11-29 03:18

    It should be:

    document.getElementById("placehere").appendChild(elem);
    

    And place your div before your javascript, because if you don't, the javascript executes before the div exists. Or wait for it to load. So your code looks like this:

    <html>
    
    <body>
    <script type="text/javascript">
    window.onload=function(){
    var elem = document.createElement("img");
    elem.setAttribute("src", "http://img.zohostatic.com/discussions/v1/images/defaultPhoto.png");
    elem.setAttribute("height", "768");
    elem.setAttribute("width", "1024");
    elem.setAttribute("alt", "Flower");
    document.getElementById("placehere").appendChild(elem);
    }
    </script>
    <div id="placehere">
    
    </div>
    
    </body>
    </html>
    

    To prove my point, see this with the onload and this without the onload. Fire up the console and you'll find an error stating that the div doesn't exist or cannot find appendChild method of null.

    0 讨论(0)
  • 2020-11-29 03:22
    document.getElementById("placehere").appendChild(elem);
    

    not

    document.getElementById("placehere").appendChild("elem");
    

    and use the below to set the source

    elem.src = 'images/hydrangeas.jpg';
    
    0 讨论(0)
  • 2020-11-29 03:22
    function image()
    {
        //dynamically add an image and set its attribute
        var img=document.createElement("img");
        img.src="p1.jpg"
        img.id="picture"
        var foo = document.getElementById("fooBar");
        foo.appendChild(img);
    }
    
    <span id="fooBar">&nbsp;</span>
    
    0 讨论(0)
  • 2020-11-29 03:24

    The following solution seems to be a much shorter version for that:

    <div id="imageDiv"></div>
    

    In Javascript:

    document.getElementById('imageDiv').innerHTML = '<img width="100" height="100" src="images/hydrangeas.jpg">';
    
    0 讨论(0)
提交回复
热议问题