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?
<html> <script type="text/javascript"> var elem = document.createElement("img"); elem.setAttribute("src", "images/hydrangeas.jpg"); elem.setAttribute("height", "768"); elem.setAttribute("width", "1024"); elem.setAttribute("alt", "Flower"); document.getElementById("placehere").appendChild("elem"); </script> <body> <div id="placehere"> </div> </body> </html>
Create Image Element in JavaScriptCreate an image element using the createElement() method on the document object. Then, set an image URL to its src attribute. Finally, add the image element to the DOM hierarchy by appending it to the body element.
document.getElementById("placehere").appendChild(elem);
not
document.getElementById("placehere").appendChild("elem");
and use the below to set the source
elem.src = 'images/hydrangeas.jpg';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With