views:

43

answers:

1

If I open a browser dialog with window.open, can I move HTML DOM object back and forth?

I know how to use jQuery's .detach() to move stuff (with all bound events) within the page. I wonder if there is a way to do it between a page and it's child dialog.

The main purpose is to support a "detach" or "tear off" functionality for a widget on a page, into a separate dialog/window.

+1  A: 

You're not supposed to be able to move a DOM Node from one ownerDocument to another. DOM Level 1 Core says you will get a DOMException with code WRONG_DOCUMENT_ERR. The proper thing to do is to call document.importNode to get a new copy of the content. (There is also document.adoptNode to do it without the copying, but it's newer, arriving in DOM Level 3 Core.

However:

  1. in the specific case of non-XML HTML documents, many browsers will let you get away with using nodes from one document in another ownerDocument.

  2. IE doesn't support importNode. (Or adoptNode, obviously.) You can either fallback to inserting the nodes directly when importNode is unavailable, or make a copy of the content in the new document manually, either by DOM-walking or HTML serialisation/parsing. (Both of those will lose information; don't expect to recover arbitrary properties or EventListeners/IE-attached-events.)

  3. There can be some issues with having the event path in one document go into code from another document, in IE6-7. When the documents are closed/navigated-away you can get some unexpected behaviours.

In any case, jQuery is not built for this. It encapsulates a reference to the owner document in itself, so when you call $ from code that originated in document A, you'll be using the document object for document A, even if your nodes and event path are now in document B. This will cause a great deal of confusion. With jQuery it is best to keep one copy of the library for each document, and use only that copy to interact with that document.

bobince