Welcome to Atalasoft Community Sign in | Join | Help

Passing DOM elements from one frame to another

I came across an interesting problem with Internet Explorer and Safari this week:

I wanted to take an arbitrary html element that had been created on a page, and send it to an iframe that was on the same page.

I created a simple test page with an iframe, a div tag, and a button.  After a few lines of JavaScript, I had it working in FireFox.  When I tested it in IE 7, it gave me an "Invalid argument" exception, and didn't specify what was invalid.  This doesn't work in Safari either.  Opera handles it exactly like FireFox.

After tinkering with it for a while, I thought it might have something to do with the ownerDocument property on the DOM element. I thought that if I could change that property, that I may be able to get it to work.  You can't change this property directly... so I thought maybe by removing the object from the parent object, it would allow me to append it to another document.  This doesn't work either.

Everything that I tried ended up not working, so as a last resort, I decided to create a copy of the element on the child frame.  This works for me, but could be missing some attributes that may be important to someone else.

I made a test page that allows you to test both the direct appendChild method, and the copy code below, while logging all errors that occur.  You can see that this test page works in both IE 7 and Safari when the checkbox is checked.

Here is the code that I used to copy the element on the child frame's document:

// o : DOM object to copy
// childDoc : document object from the child frame
function CopyToChildObject(o, childDoc){
   // create a new object on the other document
   var n = childDoc.createElement(o.tagName);
  
   // copy everything inside this tag
   n.innerHTML = o.innerHTML;
  
   // copy attributes
   for (var i in o){
      try{
         n.setAttribute(i, o.getAttribute(i));
      }
      catch (e){
         // do nothing with errors
      }
   }

   // copy style  
   for (var i in o.style){
      try{
         n.style[i] = o.style[i];
      }
      catch (e){
          // do nothing with errors
      }
   }
  
   return n;
}
Published Friday, March 14, 2008 9:35 PM by David Cilley
Filed under: ,

Comments

Saturday, April 05, 2008 6:48 AM by java internet explorer

# java internet explorer

Anonymous comments are disabled