TiredofGoogling TiredofGoogling - 2 years ago 98
HTML Question

Select Div of Element in Iframe

I have two pages on the same domain. Home.html and page2.html are their names.

home.html has the following content

<iframe id="one" src="page2.html" style="display:none"></iframe>
<div id="container">
<h1>Title of Page</h1>
<div id="ShowHere"></div>

page2.html has the following content.

<div id="container">
<span id="target">Some Text</span>
<span>Don't Show This Text</span>

I would like to use some javascript to get the contents of "target" from within the iframe with Id="one" on the page home.html and then change the innerhtml of the element id=ShowHere to show the html within the element "target" such that, it shows the words "Some Text" under the word "Title of Page".

I think that the following is a start, put at the bottom of home.html:

var frameSource = document.getElementById("one").contentWindow.document.documentElement.outerHTML;
document.getElementById("ShowHere").innerHTML = frameSource;

I've searched around and seen a few answers that supposedly do this, but none which provide a meaningful explanation of HOW to do this, and none which I can get to work. I'd prefer to use plain vanilla javascript, but Jquery is alright too.

Based on what I am trying to do, which is get the content (i.e. innerhtml) of a div from another page on the same domain, I wonder if there is a better approach than creating an invisible iframe and then reading it. Answers which achieve the desired result, but through another mechanism are also welcome.

Answer Source

Using the answer for this question

So, firstly you have to find the iframe:

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

Then you should get the iframe contents:

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

And now you can use getElementById to find DOM-elements in the iframe:

var iframeContent;

if (iframeDocument) {
    iframeContent = iframeDocument.getElementById('target').innerHTML;

Now in the iframeContent you have the contents of span you need to show on the main page, so you can just find element where you want to display iframeContent and set the innerHTML property:

var divToShow = document.getElementById('ShowHere');
divToShow.innerHTML = iframeContent;

And that's all.
I hope my answer will help you to solve your problem.
Thanks : )

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download