1

I've tried this but it did not work.

Here is my code: JSFiddle

<script src='jquery.js' type='text/javascript'></script>
<div id="body">
<textarea id="html"></textarea>
<textarea id="javascript"></textarea>
<textarea id="css"></textarea>
<iframe id='result'>
</iframe>
</div>
<script>
    var iframe_ = $("iframe#result")[0].contentDocument.document;
    console.log(iframe_);
    var iframe = $("body", iframe_);
    var script = document.createElement( 'script' );
    script.type = 'text/javascript';
    iframe.append(script)
    iframe.append("<style type='text/css'></style><div id='r'></div>");
    $("div#body").css({
        background: "#f0f0f0",
        padding: "5px",
        width: "80%"
    });
    $("iframe#result, textarea#html, textarea#css, textarea#javascript").css({
        width: "45%",
        margin: "2.5px",
        height: "250px",
        border: "1px solid #ccc",
        resize: "none",
        background: "#fff"
    }).on("keyup", function(){
        iframe.find("script").text = $("textarea#javascript").val();
        iframe.find("style").html($("textarea#css").val());
        iframe.find("div#r").html($("textarea#html").val());
    });
</script>

My problem is that I want to append html to an iframe but it is not working. It is always putting the html to append outside of the iframe.

3
  • There's a great tutorial on how to do exactly what you want here: code.tutsplus.com/tutorials/…. Very concise and easy to follow...used it on one of my projects.
    – jme11
    Commented Jun 18, 2014 at 18:37
  • 1
    var iframe = $("iframe#result").contents().find("body"); Commented Jun 18, 2014 at 18:38
  • Be careful how you are adding the new elements - your current set up looks like it will be continually adding new blocks and not updating the existing blocks which will cause you errors further down the line
    – JRulle
    Commented Jun 18, 2014 at 20:08

1 Answer 1

2

$("iframe#result")[0].contentDocument.document returns undefined.

$("iframe#result")[0].contentDocument would be correct.

PS: $("iframe#result").contents().find("body") works as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.