[javascript] Access iframe elements in JavaScript

I have a webpage where there is a textarea within an iframe. I need to read the value of this textarea from its child page using 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.

Can anyone please give me any pointers to resolve this issue?

This question is related to javascript iframe

The answer is


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

not working for me but I found another solution. Use:

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

I checked it on Firefox and Chrome.


You should access frames from window and not document

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

Two ways

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

OR

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

this code worked for me:

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

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>