Cannot appendChild create node from another frame

I have a iframe page and would like to extract the DOM node from the child frame and put it on the parent page. This works in Firefox (3.5), but not in Internet Explorer (7).

I broke the code into the simplest option.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html> <head> <title>Fragment</title> </head> <body> <iframe src="blank.html"></iframe> <script type="text/javascript"> window.onload = function () { var fragment = document.createDocumentFragment(); var div = frames[0].document.createElement("div"); fragment.appendChild(div); }; </script> </body> </html> 

I get the error " Invalid argument " in the line " fragment.appendChild(div); ". The error seems to be due to the fact that I am creating a document fragment from an iframe document and a div element from the parent document. This code works if both use the same document.

I want to save any events that can be attached to DOM nodes, so I don't want to use innerHTML.

Does anyone know a fix for this?

+4
source share
3 answers

Your problem is that you are not embedding nodes in the fragment created in the current document. Use either of the following:

 fragment.appendChild(fragment.ownerDocument.createElement("div")); 

or

 fragment.appendChild(fragment.ownerDocument.adoptNode(document.createElement("div")); 
+4
source

I just risk assuming, but you can try creating a div using

 var div = frames[0].document.createElement("div") 

instead

 var div = document.createElement("div") 

Using the main document method createElement () may be due to IE having a problem.

+2
source

I think I found the answer here: http://www.alistapart.com/articles/crossbrowserscripting/

Importing documents from two different ownerDocument properties requires the use of the DOM level 2 importNode () method, because in these cases the DOM will not allow simple document.appendChild ().

0
source

Source: https://habr.com/ru/post/1301628/


All Articles