0

I'm new to Javascript so I apologize for this relatively easy question. I have a picture that I'm interested in appending to the bottom of a container (wrapper). I've experimented with append(), appendChild(), prepend() with relatively little success, so I'm wondering if it's the sequence I'm declaring things or just another bug.

$("#imageLocation").appendTo(wrapper);

img.setAttribute("src", params.imageurl);
img.setAttribute("class","imagelink");
document.getElementById("imageLocation").appendChild(img);

imageLocation, imagelink have all been declared in my CSS file, but I'm getting the following error: Uncaught TypeError: Cannot call method 'appendChild' of null.

What other things should I be looking at? Thanks!

2 Answers2

0

With JQuery you can do this:

$('<img />').attr('src','file.png').addClass('some-class').appendTo('.container');

This will create the image element, set image source, add class and finally append all to container in DOM.

Hardy
  • 5,590
  • 2
  • 18
  • 27
0

If you want to append the image with Javascript, you could do it like this:

var img = document.createElement('img');
img.setAttribute("src", params.imageurl);
img.setAttribute("class","imagelink");
document.getElementById("imageLocation").appendChild(img);

However, the error message suggests, that document.getElementById("imageLocation") returns null, which means there is no element with the id imageLocation.

Make sure the id is correct and the script is executed after the element is created by the browser.

This can be done by placing the script at the bottom of the page or using this. If you are using jQuery, you can wrap the code inside

$('document').ready(function () {
    //code to execute
});
Community
  • 1
  • 1
Simon
  • 168
  • 6