How to access parent iframe elements from a child

2019-01-26 09:39发布

问题:

I have 2 pages-- Parent n child.

In the parent page i have an iframe whose value i want to fetch in the javascript of child page. Is there any way?....Please suggest.

回答1:

actually only iframeElement is needed.

from inside child document:

 var iframe = frameElement;

and you're done.



回答2:

Assuming that your page and frame structure is as follows

parent (contains iframe)
   |--> child page (attempts to access iframe in parent)

and that

  1. the src of the iframe and other pages is the same
  2. the name of the iframe is 'iFrame',

you can access an element named 'iFrameElement' in the iframe using the following JavaScript statement from the child:

parent.frames['iFrame'].document.getElementById('iFrameElement').value;

or simply the following from the parent containing the iframe

frames['iFrame'].document.getElementById('iFrameElement').value;

Since the frame name is indeterminate at runtime, you could revert to using the frame number in the window.frames array, as follows (from the child)

//assuming frames[0] refers to the iframe
parent.window.frames[0].document.getElementById('iFrameElement').value;

or from the parent

//assuming frames[0] refers to the iframe
window.frames[0].document.getElementById('iFrameElement').value;


回答3:

Use

parent.getElementById('elementId').value;

to get the element. If you have multiple nested iframes, you can get the root parent by using

top.getElementById('elementId').value;

Either will work in your case.



回答4:

You can use

window.parent.getElementById('YOUR ID').value();

to get the value from the input element with the id "YOUR ID" from the parent.



回答5:

Try giving a name to your iframe and acess the iframe like this

window.parent.<iframe_name>.document.getElementById()


回答6:

You can get iframe's element in parent's document from inside the iframe this way:

var iframe = parent.document.getElementById(window.frameElement.id);