简体   繁体   中英

How to insert an img tag in an iframe in js?

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 class="fruit"> <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?

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);

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM