I have an img tag in my document. I want to insert it into an iframe tag I created. Here is my code:
var ARiframe = document.createElement("iframe");
const imgInDom = document.getElementById("apple_img");
imgInDom.parentNode.insertBefore(ARiframe, imgInDom);
ARiframe.appendChild(imgInDom);
<html>
<body>
<div >
<img id="apple_img" src="https://parade.com/.image/t_share/MTkwNTgxNDY1MzcxMTkxMTY0/different-types-of-apples-jpg.jpg" width="100" height="100">
</div>
</body>
</html>
I am able to insert my img tag into the frame tag. However, the image itself does not display when in the iframe. I think the reason for this could be that the img tag is outside the #document
for the iframe (look at the inspect button for the DOM). So, how would I put it in the iframe correctly so that the image displays?
CodePudding user response:
Append it to the contentDocument.body
of the <iframe>
.
var ARiframe = document.createElement("iframe");
const imgInDom = document.getElementById("apple_img");
imgInDom.parentNode.insertBefore(ARiframe, imgInDom);
ARiframe.contentDocument.body.appendChild(imgInDom);