Access iframe elements in JavaScript

133,459

Solution 1

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

// replace myIFrame with your iFrame id
// replace myIFrameElemId with your iFrame's element id
// you can work on window.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.

Solution 2

You should access frames from window and not document

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

Solution 3

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>

Solution 4

this code worked for me:

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

Solution 5

Two ways

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

OR

window.frames['myIFrame'].contentWindow.document.getElementById('myIFrameElemId')
Share:
133,459
archana roy
Author by

archana roy

Updated on April 17, 2021

Comments

  • archana roy
    archana roy over 1 year

    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?

  • archana roy
    archana roy about 13 years
    Thanks a lot for your suggestions. But the problem is that the frame id n frame name in my parent page changes in runtime, hence we cannot use the frame id/frame name for reference. Is there any other way Ra Yell?..
  • archana roy
    archana roy about 13 years
    Bith parent n child page are in same domain.
  • RaYell
    RaYell about 13 years
    If there is ony one iframe on your site you could try using document,frames[0].document. If there are more you need to change the index to some other value.
  • tylerl
    tylerl over 10 years
    document.frames no longer works. Use window.frames instead.
  • Ciaran Phillips
    Ciaran Phillips almost 9 years
    To confirm what @tylerl said, I just checked in Firefox 25 and Chrome 31. In both cases document.frames was undefined, but window.frames worked perfectly
  • Gaurav
    Gaurav over 7 years
    Wow, didn't realize I downvoted this instead of upvoting. And now it's too late to undo. Apologies!
  • svnm
    svnm about 7 years
    .contentDocument rather than document works for me