75

I have a webpage where there is a textarea within a iframe. I need to read the value of this textarea from its child page JavaScript. Presently by using window.parent.getelementbyID().value in the JavaScript, I am able to fetch values of all controls in the parent page except the textarea within the iframe.

The frame id and frame name in my parent page changes in runtime, hence we cannot use the frame id/frame name for reference.

3

2 Answers 2

90

If you have the HTML

<form name="formname" .... id="form-first">
    <iframe id="one" src="iframe2.html">
    </iframe>
</form>

and JavaScript

function iframeRef( frameRef ) {
    return frameRef.contentWindow
        ? frameRef.contentWindow.document
        : frameRef.contentDocument
}

var inside = iframeRef( document.getElementById('one') )

inside is now a reference to the document, so you can do getElementsByTagName('textarea') and whatever you like, depending on what's inside the iframe src.

Sign up to request clarification or add additional context in comments.

5 Comments

Just 1 concern Meder-- var inside = iframeRef( document.getElementById('one') ) The frameid n framename in my page changes in runtime, so it wont be possible to pass the frameid(as done by you). Is there any other alternative?
yes. getElementsByTagName('iframe') to refer to a nodeList and access elements inside with [0], assuming you're dealing with one. or you can do a loop.
Thanks Meder. Just 1 more query-- Whats the difference between-- 'frameRef.contentWindow.document' and 'frameRef.contentDocument' I want to understand the concept behind this. It would be really good of you,if you explain it a bit. Thanks a lot for your help.
An explanation can be found @ xkr.us/articles/dom/iframe-document Some browsers support one of those dom properties, and I just check for either.
You r a genius Meder. Thanks a ton for your instant help.
19

Using jQuery you can use contents(). For example:

var inside = $('#one').contents();

1 Comment

An important consideration here is that the contents method can "get the content document of an iframe, if the iframe is on the same domain as the main page."

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.