Coder Perfect

In Javascript, how can I access the content of an iframe’s body?


<iframe id="id_description_iframe" class="rte-zone" height="200" frameborder="0" title="description">
    <body class="frameBody">

What I’m looking for is:


Asked by omg

Solution #1

The real question is how to do it without jQuery and with pure JavaScript.

However, I always utilize the solution found in the jQuery source code. It’s only one line of JavaScript native code.

It’s the best, most readable, and, afaik, quickest way to retrieve the iframes content for me.

Get your iframe first.

var iframe = document.getElementById('id_description_iframe');

// or
var iframe = document.querySelector('#id_description_iframe');

Then you can utilize jQuery’s solution.

var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

In the iframe, select the elements you want to use.

Then you can generally choose the DOM-Element from the iframeDocument using getElementById() or even querySelectorAll():

if (!iframeDocument) {
    throw "iframe couldn't be found in DOM.";

var iframeContent = iframeDocument.getElementById('frameBody');

// or
var iframeContent = iframeDocument.querySelectorAll('#frameBody');

In the iframe, call functions

To call some global functions, variables, or entire libraries (e.g. jQuery), get simply the window element from the iframe:

var iframeWindow = iframe.contentWindow;

// you can even call jQuery or other frameworks
// if it is loaded inside the iframe
iframeContent = iframeWindow.jQuery('#frameBody');

// or
iframeContent = iframeWindow.$('#frameBody');

// or even use any other global variable
iframeWindow.myVar = window.myVar;

// or call a global function
var myVar = iframeWindow.myFunction(param1 /*, ... */);


All of this is achievable if the same-origin policy is followed.

Answered by algorhythm

Solution #2

Try this with JQuery:


Answered by Michael Adedayo

Solution #3

For me, it works perfectly:


Answered by bizzr3

Solution #4

An Iframe, AFAIK, cannot be utilized in this manner. You’ll need to change the source attribute to point to another page.

Here’s how to extract the content of its body using plain old javascript. This works in both Internet Explorer and Firefox.

function getFrameContents(){
   var iFrame =  document.getElementById('id_description_iframe');
   var iFrameBody;
   if ( iFrame.contentDocument ) 
   { // FF
     iFrameBody = iFrame.contentDocument.getElementsByTagName('body')[0];
   else if ( iFrame.contentWindow ) 
   { // IE
     iFrameBody = iFrame.contentWindow.document.getElementsByTagName('body')[0];

Answered by Jose Basilio

Solution #5

use JS to render content in an iframe:


Answered by CoursesWeb

Post is based on