Accessing the document inside an iframe

When dealing with inline frames (iframe), it is common to have the need to access the document loaded into the iframe.


In order to support the most browsers with the least headaches, it is best to use the highly-compatible "DOM0" frames collection, which is a child of window.

For example, to reference an element with id="foo" in a frame with name="loader_frame", one would use the following syntax:

var elFoo = window.frames['loader_frame'].document.getElementById('foo');

Of course you can omit the window. when referencing the frames collection of the current window because window is the default scope.

For those developers who want more standardized DOM-centric code, I bring you the most compatible (current) cross-browser method for acessing the document contained within an iframe, directly via the iframe object in the DOM.

Browser Disagreements

contentWindow vs. contentDocument

Because Safari has no way to directly access the window object of an iframe element via standard DOM (or does it?), our fully modern-cross-browser-compatible code will only be able to access the document within the iframe. The resulting code follows.

Summary & Code

In summary, to access the document loaded inside an iframe, use:


Here is a working example that modifies the backgroundColor of the body of the document contained in the iframe:


This code has been tested on and is known to work in:

This code is known to not work in: