Why inserting the same image object twice in html does not work?

Viewed 1162

I'm trying to insert the same image into two different divs. But the image is only displayed in the last one. It looks like the same object can only appear once in html.

var img = new Image();
img.src = '/image1.jpg';
img.onload = function(){
   $('#div1').html(img);
   $('#div2').html(img);
}

Only #div2 display the image.

Update to add code snippet

var img = new Image();

img.src = "http://via.placeholder.com/350x150";
img.onload = function(){
    img.id = '#jcrop-target';
    $('#jcrop').html(img);
    img.id = '#jcrop-preview';
    $('#preview').html(img);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="jcrop"></div>
<div id="preview"><div>

I used this solution, but it seemed very inelegant.

var img = new Image();

img.src = 'http://via.placeholder.com/350x150';

img.onload = function(){
   $('#jcrop').html('<img id="jcrop-target" src="'+img.src+'" />');
   $('#preview').html('<img id="jcrop-preview" src="'+img.src+'" />');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="jcrop"></div>
<div id="preview"></div>

3 Answers
Related