Cloning element

I would like to copy/clone html element to spare some lines of javascript code and probably performance because I will be using this frequently.
I tried with something simple (div), but can't make it work.
My environment:
 - parent document
 - nested iframe document

Parent document contains: <div id='myDiv' style='display:none;'>this is my div</div>
and javascript:
el = iframeDoc.body.appendChild(document.getElementById("myDiv").cloneNode(false));"inline";

This line of javascript code is called from iframe and doesn't work. It reports "invalid argument" error.
If I runtime create element (createElement()) and append it to the iframe document body then it works. Where's the catch?

Who is Participating?
I don't think you can even append a node in your frame document if you created it with document.createElement() (document being the parent document).
You can if you use frameDoc.createElement and then append it to frameDoc.
In fact, a node belongs to a document object and can not be appended to another document object.
By the way, looks like Firefox enables this kind of operation, tried your simple code and it works.
hpetAuthor Commented:
I know, but it doesn't work in IE.
It works without problems if I createElement, setAttribute, and then append. but I have some idea in my head that makes me think that cloning an existing node will be faster and easier if I will use this on frequent basis (cloning vs. always newly create and set everything).

Now that you brought up document objects, it makes sence, and not... if I clone node then specification says it is just a copy of object not belonging anywhere until you append it. It should behave the same way as if I manualy create it.

I think cross document object restrictions shouldn't apply here because I am calling this script from the document object I want to append clone to.
hpetAuthor Commented:
I think I have found explanation:

...and here we are... oh, I just love it.

I think I will stick to createElement, appendElement since it appears to be less a trouble (I don't have that many elements to create anyhow. Cloning will be left for better days.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.