Denny J.
Denny J.

Reputation: 249

Create an <iframe> element and append html content to it with jQuery

Is it possible using jQuery to create an <iframe> element and append html content to it without having src attribute specified?

The problem is I need to create an iframe and I already have its content (I get it as AJAX response). Unfortunately, I can't specify the URL I get response from as src attribute. I'd like to do something like:

$('<iframe id="someId"/>').append(response).appendTo("#someDiv");

Upvotes: 17

Views: 45483

Answers (3)

Mehdi Dehghani
Mehdi Dehghani

Reputation: 11601

Accepted answer doesn't work for me, but following solution works:

$('<iframe>', {
    id: 'someId',
    // other options like
    frameborder: 0,
    scrolling: 'no'
}).appendTo('#someDiv').on('load', function () {
    $(this).contents().find('body').append(response);
});

Upvotes: 0

Surreal Dreams
Surreal Dreams

Reputation: 26380

Why use an iframe then? Stick it all in another container. I can't think of any advantage of the iframe except that you can load a page from a src attribute.

I suppose if you need an iframe for some other purpose, like you load in a page but you want to replace it with the ajax response, you could use jQuery to swap out the iframe for a div and back again as needed.

The other possibility is that instead of ajax, modify your ajax php script to output the full page that you want in the iframe. Then use jQuery to change up the address of the requested page in the iframe with new parameters to display updated content.

Upvotes: 2

user113716
user113716

Reputation: 322492

Try this:

$('<iframe id="someId"/>').appendTo('#someDiv')
                          .contents().find('body').append(response);

Upvotes: 38

Related Questions