Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

javascript – How to move an img tag into a div without reloading the image?

const div = document.createElement('div');
const span = document.createElement('span');
const img = document.querySelector('img');
const imgCloned = img.cloneNode();
div.appendChild(imgCloned);
div.append(span);
img.replaceWith(div);

It is working and the img is being moved into the div element, however, because it is a cloned image, there is another request to get the image. How can I move the img into the div without reloading the image?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

re-order what you’re doing

replace the image and then add the image to the beginning of the div

const div = document.createElement('div');
const span = document.createElement('span');
const img = document.querySelector('img');
div.append(span);
img.replaceWith(div);
div.insertAdjacentElement('afterbegin', img);
<div>
  The image is here
  <img src="https://placekitten.com/200/300">
  <span> other things live here </span>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading