syard gate
syard gate

Reputation: 85

get all content of div including content of iframes using javascripts not jquery

I Have a div something like this

<div id="tid">
   <iframe>
       <html>
           <body>
           <scripts></scripts>
           <iframe>...
              //more content
           <ifram>
           </body>
       </html>
   </iframe>
</div>

I want to get below using javascript.

<iframe>
    <html>
        <body>
           <scripts></scripts>
               <iframe>...
                  //more content and cannot guess how many iframes are there.
              <ifram>
         </body>
     </html>
</iframe>

InnerHtml only return first iframe only. I tried with .contentDocument.getElementsByTagName('body')[0].innerHTML. but this only return first iframe. I want get all the content into string variable without using jquery.

Thanks

Upvotes: 1

Views: 1142

Answers (4)

syard gate
syard gate

Reputation: 85

can not do this because of same origin policy

Upvotes: 0

CJ Ramki
CJ Ramki

Reputation: 2630

YOU NEED TO REPLACE < WITH &lt; AND > WITH &gt; TO PRINT HTML TAGS AS A PLAIN TEXT.

try this code,

 var content = document.getElementById('tid').innerHTML;
 content = content.replace(/</g,"&lt;").replace(/>/g,"&gt;"); 
 document.getElementById('content').innerHTML = content;

SEE THIS DEMO

if you want to reuse that div html, simply add that content to any other html element like below,

 var content = document.getElementById('tid').innerHTML;
  //the variable content contains the html inside "tid" div.
  var iDiv = document.createElement('div');
iDiv.id = 'newDiv';
iDiv.innerHTML = content;
document.getElementsByTagName('body')[0].appendChild(iDiv);

SEE THIS DEMO

Upvotes: 6

Sajjad Ashraf
Sajjad Ashraf

Reputation: 3844

Do this

var iframe = document.getElementById('iframeID');
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;

now you can use iframeDocument to access content of iframe, jquery does the same

UPDATE

You can do something like this ..

var myDiv = document.getElementById("tid");
var iframes = myDiv.getElementsByTagName("iframe");

// now loop over the iframes 

for(iframe in iframes){
  var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
  var internalIframes = iframeDocument.getElementsByTagName("iframe");
  if(internalIframes.length > 1){
     // start the for in loop again
  }

}

Upvotes: 1

imtheman
imtheman

Reputation: 4843

If you only want the body tags this should work.

var els = document.getElementsByTagName("body");
var allContent = "";

for (var i=0; i < els.length; i++) {
     allContent += els[i].innerHTML;
}

Upvotes: 1

Related Questions