javascript document.getElementById in other frames

61.2k views Asked by At

I have two frames and want to access an element in one frame from another:

Frame 1:

<div id='someId'>...</div>

Frame 2:

var div=document.getElementById('someId');

div.innerHTML='something'; 

This is somehow not functioning in Firefox so I want to be sure, can I access an element in another frame by its ID?

7

There are 7 answers

4
rahul On BEST ANSWER

You can refer the other frame by using

window.frames["framename"]

and then you can refer the element in the DOM by using

window.frames["framename"].document.getElementById ( "yourelementid" );
0
Brian Duncan On

The issue may be the current frame you are in. If window.frames['framename'] does not work, try parent.frames['framename'] to access the top level frames.

if(parent.frames && parent.frames['framename']) {
   var elem = parent.frames['framename'].document.getElementById(...); 
   // etc
}
0
Pablo Martinez On

Simply use frameId.MyElementId

Of course, when defining your frame, not enough to use "name=....", rather use "id=..." within your frame tag. E.g.:

    <iframe id=MyFrame> .... 
          <input id=MyElementId>
               ...

    <script>
       // do something with MyElementId
           MyFrame.MyElementId.value = "something";

At least, it works as of 2022 (almost 2023).

[Note that I didn't even use "name"... that's quite not necessary by these days, unless you want to use radio buttons with multiple <INPUT's that refer to the same mutually exclusive element]

0
Erisan Olasheni On
document.getElementById('frameId').contentDocument.getElementById('frameChild');
0
goodhyun On

Or, if you feel like trying your luck, you can just use a numeric parameter.

window.frames[0].document

0
Flea On

I was having problem with the JS version but was able to use these examples for a working jQuery version:

var obj = $('#yourelementid', parent.frames["framename"].document);
0
drset On

For some reason

window.frames["framename"].document.getElementById ( "yourelementid" );

was not working for me.

This other method did:

   document.getElementById('framename').contentWindow.document.getElementById('yourelementid');