Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

iframe

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");
like image 775
Denny J. Avatar asked Nov 07 '10 22:11

Denny J.


People also ask

Can you use jQuery in an iframe?

However, it's also possible to use a really simple jQuery to access the elements within the iFrame. Check it out below: $(document). ready(function(){ var iFrameDOM = $("iframe#frameID").

How do I add HTML content to an iframe?

Answer: Use the jQuery contents() method You can use the jQuery contents() method in combination with the find() , val() and html() methods to insert text or HTML inside an iframe body.

Can you put a div inside an iframe?

Approach 1: For adding additional div's in an iframe, you need to use a wrapper div, that wraps the contents of your intended div and the iframe into one unit. This way you can display the contents of your div along with the iframe embedding to the document/webpage.


2 Answers

Try this:

$('<iframe id="someId"/>').appendTo('#someDiv')
                          .contents().find('body').append(response);
like image 137
user113716 Avatar answered Sep 22 '22 12:09

user113716


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.

like image 38
Surreal Dreams Avatar answered Sep 24 '22 12:09

Surreal Dreams