title: What's the most concise cross-browser way to access an <iframe> element's window and document?
body: <p>I'm trying to figure out the best way to access an <code>&lt;iframe&gt;</code> element's <code>window</code> and <code>document</code> properties from a parent page. The <code>&lt;iframe&gt;</code> may be created via JavaScript or accessed via a reference stored in an object property or a variable, so, if I understand correctly, that rules out the use of <code>document.frames</code>.</p>
  
  <p>I've seen this done a number of ways, but I'm unsure about the best approach. Given an <code>&lt;iframe&gt;</code> created in this way:</p>
  
  <pre><code>var iframe = document.createElement('iframe');
  document.getElementsByTagName('body')[0].appendChild(iframe);
  </code></pre>
  
  <p>I'm currently using this to access the <code>document</code>, and it seems to work OK across the major browsers:</p>
  
  <pre><code>var doc = iframe.contentWindow || iframe.contentDocument;
  if (doc.document) {
    doc = doc.document;
  }
  </code></pre>
  
  <p>I've also see this approach:</p>
  
  <pre><code>var iframe = document.getElementById('my_iframe');
  
  iframe = (iframe.contentWindow) ? iframe.contentWindow :
           (iframe.contentDocument.document) ? iframe.contentDocument.document :
           iframe.contentDocument;
  
  iframe.document.open();
  iframe.document.write('Hello World!');
  iframe.document.close();
  </code></pre>
  
  <p>That confuses me, since it seems that if <code>iframe.contentDocument.document</code> is defined, you're going to end up trying to access <code>iframe.contentDocument.document.document</code>.</p>
  
  <p>There's also this:</p>
  
  <pre><code>var frame_ref = document.getElementsByTagName('iframe')[0];
  
  var iframe_doc = frame_ref.contentWindow ? frame_ref.contentWindow.document :
      frame_ref.contentDocument;
  </code></pre>
  
  <p>In the end, I guess I'm confused as to which properties hold which properties, whether <code>contentDocument</code> is equivalent to <code>document</code> or whether there is such a property as <code>contentDocument.document</code>, etc.</p>
  
  <p>Can anyone point me to an accurate/timely reference on these properties, or give a quick briefing on how to efficiently access an <code>&lt;iframe&gt;</code>'s <code>window</code> and <code>document</code> properties in a cross-browser way (without the use of jQuery or other libraries)?</p>
  
  <p>Thanks for any help!</p>