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

Viewed 43
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?

2 Answers

Just move it to the created div ...

This little stackblitz project has a function to move an image, fork it to play with the code.

const div = document.createElement('div');
const span = document.createElement('span');
div.append(document.querySelector('img'));
div.append(span);
document.body.insertBefore(div, document.body.firstChild);
document.querySelector(`pre`).textContent = 
  document.body.querySelector(`div`).outerHTML;
<img src="https://picsum.photos/200/300">
<h3>Your html after move</h3>
<pre></pre>

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>

Related