TiredofGoogling TiredofGoogling - 7 months ago 12
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

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


page2.html has the following content.

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


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:

<script>
var frameSource = document.getElementById("one").contentWindow.document.documentElement.outerHTML;
// ANSWER TO MY QUESTION
document.getElementById("ShowHere").innerHTML = frameSource;
</script>


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

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 : )