Alex Rivera | Logout

Insert image object into HTML

Asked 2012-09-05T18:47:17.060
19

I'm just curious to know if there's a better solution for doing this:

var img = new Image();
var div = document.getElementById('foo');

img.onload = function() {
  div.innerHTML += '<img src="'+img.src+'" />'; 
};

img.src = 'path/to/image.jpg';

Desired method:

console.log(img); // <img src="path/to/image.jpg" />
div.innerHTML += img;

Thoughts?

Edit
Report

1 Answer

2

You can use this way:

var img = new Image();
var div = document.getElementById('theDiv');

img.onload = function() {
  div.appendChild(img);
};

img.src = 'path/to/image.jpg';
answered 2012-09-05T18:50:00.350

Your Answer