简体   繁体   中英

Can I move a DOM node from an iFrame to parent's body?

Currently I'm trying to move a DOM node by using the following snippet:

var element = document.getElementById('my-id');
parent.window.body.appendChild(element);

The code above is rendered within an iFrame, but I'm getting the exception "parent.window.body is undefined". Is this a security feature (since I effectively do want to break out of the iframe)?

Please note: I do not want to re-ask "how to move a DOM node" per se , but to move it across borders of an iframe!

Yes, you can, within the same origin . (Checked on Firefox, Chrome, IE8, IE11, and Edge.) Note that when you do so, any event listeners attached to it remain attached, which could be confusing. Also note that the old DOM3 spec allowed for an error if the node was being appended to a different document, but the more recent WHAT-WG DOM spec doesn't mention doing that (if you start at appendChild and follow through, you end up here , which doesn't have that exception listed).

But body isn't a property of the window, it's a property of the document . Also note that parent.window is redundant. So:

parent.document.body.appendChild(element);
// ----^

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