Bill Dami
Bill Dami

Reputation: 3225

Replacing entire contents of iframe (including doctype & html tags) with jQuery

There are quite a few other posts on stackoverflow that ask nearly the same question, but in all the answers I've read so far, they don't address how to essentially replace the entire document of the iframe, including the DOCTYPE and html tags.

I am retrieving the HTML for an entire page via a jQuery.ajax request and attempting to use the returned HTML as the new HTML of the iframe. Here's an example of the HTML being returned from the ajax request:

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <link rel="stylesheet" type="text/css" media="all" href="main.css">
        <title>Test Page</title>
    </head>
    <body>
        <h1>Heading</h1>
    </body>
</html>

I then inject this HTML into the iframe via:

$('#my-iframe').contents().find('html').html(returnedHtml);

As suggested on most of the other posts on this subject. However, when I inspect the contents of the iframe, the document is structured as follows:

<html>
    <link rel="stylesheet" type="text/css" media="all" href="main.css">
    <title>Test Page</title>
    <h1>Heading</h1>
</html>

Notice the lack of DOCTYPE, missing lang attribute on the html tag, missing head and body tags.

Any suggestions? (Note that just changing the iframe's src attribute to the necessary url is not possible in this app due to various factors)

Upvotes: 0

Views: 2938

Answers (1)

adeneo
adeneo

Reputation: 318182

Try some plain javascript instead:

iframe = document.getElementById('my-iframe');
iframe.contentWindow.document.open()
iframe.contentWindow.document.write(returnedHtml);​

FIDDLE

Upvotes: 1

Related Questions