Adding an img element to a div with javascript

后端 未结 4 1579
囚心锁ツ
囚心锁ツ 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:

    
    
    
    
    

    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.

提交回复
热议问题