views:

153

answers:

2

I want to use the append() function from inside the <head>, in a function to be specific, like so:

function custom_img(src_img)
{
 $("div").append("<img src='"+src_img+"'>");
}
var myimg = new custom_img("test.jpg");

This is a quick example that I just wrote out. I want my function to make a new image like that every time I create a new object like this. Obviously this doesn't work, since the append() requires to be in the body (I've tried this).

How would I do this?

A: 

You can try using .after(), or even .html()

function custom_img(src_img)
{
 $("div").after("<img src='"+src_img+"'>");
}
var myimg = new custom_img("test.jpg");

or

function custom_img(src_img)
{
 $("div").html("<img src='"+src_img+"'>");
}
var myimg = new custom_img("test.jpg");
Tim
Both do not seem to work.
Anonymous
+1  A: 

The reason it's not working is because your div does not exist yet.
So you can either use the $(document).ready() function to wait for the document to load.

Or if you want the images to load together with the rest of the document, you could simply create a new div and insert the images there.

var div = $("div")
function custom_img(src) {
   div.append($("img").attr("src", src));
}

Then when the document is fully loaded, you can go through the array and insert the loaded images in the DOM.

$(document).ready(function() {
   $("#myDiv").append(div);
});
peirix
I am quite unsure what to do with this. I've tried putting this in a script in the head part, but there's still no result. Actually, the class is being multiple times in runtime, it keeps going. As it gets new info, it starts adding new images. Any further information you can spare?
Anonymous
@Anonymous. post more code
David Murdoch