Question

Based on an answer to this question, I am trying to append elements directly into an empty iframe with no src attribute.

However, it seems appendChild on the iframe fails silently.

In the code below, doc.write("Hello World"); works correctly, but myform2.appendChild(input2); does not change the innerHTML of the frame, and also does not throw an error.

<html>
    <body>  
     <iframe  name = "myframe" id = "myiframe"> 
     </iframe>  
    <script>
    var myform2 = document.createElement("form");
    var input2 = document.createElement("input");
    input2.name = "quantity";
    input2.value = "10";

    myform2.appendChild(input2);
        </script>

    <script>

    var getFrame = document.getElementById('myiframe');
    var doc = getFrame.contentDocument || getFrame.contentWindow.document;

//  doc.write("Hello World");
    doc.body.appendChild(myform2); // Does not work.
    </script>   
    </body>
</html>

What is the correct way to add a form into the iframe using raw Javascript?

I am looking for non-jQuery solutions, because I want to understand how the magic works, rather than just letting jQuery perform the magic.

Was it helpful?

Solution

I think it's a matter of timing. Try to run your script after document has been loaded:

<body onload="loadMe();">

    <iframe  name = "myframe" id = "myiframe"> 
    </iframe>  

    <script>

    function loadMe() {    
        var myform2 = document.createElement("form");
        var input2 = document.createElement("input");
        input2.name = "quantity";
        input2.value = "10";

        myform2.appendChild(input2);

        var getFrame = document.getElementById('myiframe');
        var doc = getFrame.contentDocument || getFrame.contentWindow.document;
        doc.body.appendChild(myform2); // Does not work.
    }    
    </script>  


</body>

http://jsfiddle.net/GR7LJ/2/

OTHER TIPS

This should work in IE 10+, Firefox, and Chrome (and maybe older versions of IE). Basically, I am just creating an iframe, selecting where to place it, placing it inside of it, then opening the new iframe's contentWindow.document and writing pure HTML/CSS/Javascript into it.

var newIframe = document.createElement("iframe");
var container = document.getElementById("container");
container.appendChild(newIframe);
var iframeContent = newIframe.contentWindow.document;
iframeContent.open();
iframeContent.write("<input type='text' />");
iframeContent.close();
newIframe.setAttribute("sandbox", "allow-scripts"); // optional sandboxing

I've run into issues before where attempting to append DOM elements does not always work so in this scenario I just pass them in as a string. I also "close" off the iframe by sandboxing it (security preference) after appending the HTML I need.

Hope this solution helps you.

Here's a fiddle: http://jsfiddle.net/fv2DB/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top