Accessing iframes in JavaScript

I have a webpage where there is a text box inside the iframe. I need to read the value of this text box from my child page using JavaScript.

Currently, using window.parent.getelementbyID().value in JavaScript, I can get the values โ€‹โ€‹of all the controls on the parent page except for the text area inside the iframe.

Can someone please give me any instructions to solve this problem?

+22
javascript iframe
Sep 20 '09 at 14:57
source share
5 answers

If your iframe is in the same domain as your parent page, you can access the elements using the document.frames collection.

 // replace myIFrame with your iFrame id // replace myIFrameElemId with your iFrame element id // you can work on document.frames['myIFrame'].document like you are working on // normal document object in JS window.frames['myIFrame'].document.getElementById('myIFrameElemId') 

If your iframe is not in the same domain, the browser should prevent such access for security reasons.

+43
Sep 20 '09 at 17:00
source share

You need to access frames from window , not document

 window.frames['myIFrame'].document.getElementById('myIFrameElemId') 
+14
Nov 01 '11 at 17:44
source share

window.frames['myIFrame'].document.getElementById('myIFrameElemId')

not working for me, but I found another solution. Using:

 window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId') 

I tested it on Firefox and Chrome.

+13
Dec 23 '13 at 19:49
source share

this code worked for me:

 window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId'); 
+2
Oct 28 '16 at 2:54 on
source share

Make sure your iframe is already loaded . Old but reliable way without jQuery:

 <iframe src="samedomain.com/page.htm" id="iframe" onload="access()"></iframe> <script> function access() { var iframe = document.getElementById("iframe"); var innerDoc = iframe.contentDocument || iframe.contentWindow.document; console.log(innerDoc.body); } </script> 
+1
Mar 14 '17 at 9:45
source share



All Articles