Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert image object into HTML

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?

like image 644
daryl Avatar asked Sep 05 '12 18:09

daryl


2 Answers

I think what you want is this:

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

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

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

You already have a loaded image object. You should just append it directly into the DOM rather than create a whole new image object with innerHTML.

In addition using += with innerHTML is very wasteful as it takes all the objects you already have in there, converts them to HTML text, adds onto that text and then makes all new DOM objects - losing all event handlers when it makes new objects too. It's way, way more efficient to just add a new DOM object onto the set of existing DOM object.

In addition, document.getElementById() takes the id without a # in front of it.

like image 57
jfriend00 Avatar answered Oct 08 '22 04:10

jfriend00


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';
like image 33
Praveen Kumar Purushothaman Avatar answered Oct 08 '22 05:10

Praveen Kumar Purushothaman