Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Write elements into a child iframe using Javascript or jQuery

I have something like this:

<!doctype html> <html>   <body>      <iframe id="someFrame"></iframe>   </body> </html> 

And I would like to use jQuery to write elements such that the full equivalent HTML would be like this:

<!doctype html> <html>   <body>     <iframe id="someFrame">       <!-- inside the iframe's content -->       <!-- <html><body>  -->       <div>A</div>       <div>B</div>       <div>C</div>       <!-- </body></html> -->     </iframe>   </body> </html> 

Alternatively, any plain-old-Javascript would be fine.

Thanks.

Edit: After a little more research, it seems I am looking for an IE-equivalent of the contentDocument property of an iframe. "contentDocument" is a W3C standard which FF supports, but IE does not. (surprise surprise)

like image 679
Jeff Meatball Yang Avatar asked Jun 15 '09 19:06

Jeff Meatball Yang


People also ask

Can you use jQuery in an iframe?

You can use jQuery to add jQuery effects to your iFrame elements, to change the CSS rules, or even to add content. Above, the script is used to change the background color of the . page element within the frame to white. Use the script for yourself and save yourself a headache next time you're working with an iFrame!

How do you write an iframe in HTML?

An inline frame is used to embed another document within the current HTML document. Tip: Use CSS to style the <iframe> (see example below). Tip: It is a good practice to always include a title attribute for the <iframe> .

How can get iframe HTML using jQuery?

# jQuery Code to Get HTML Content of IFrame$("#myButton"). on('click', function() { alert($("#myIframe"). contents(). find("html").


1 Answers

You can do both, you just have to target differently:

var ifrm = document.getElementById('myIframe'); ifrm = ifrm.contentWindow || ifrm.contentDocument.document || ifrm.contentDocument; ifrm.document.open(); ifrm.document.write('Hello World!'); ifrm.document.close(); 
like image 83
Mike Robinson Avatar answered Oct 08 '22 19:10

Mike Robinson