user3719477
user3719477

Reputation: 110

Append HTML to an iframe using jQuery

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.

Upvotes: 1

Views: 2127

Answers (1)

StrubT
StrubT

Reputation: 1028

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

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

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

Upvotes: 2

Related Questions