0

When I try to access the iframe, I get this error and I'm not sure what i'm doing wrong. Can someone help me out with this problem?

var ifrm = document.getElementById('iframe'), ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument; ifrm.open(); ifrm.write("Hello World!"); ifrm.close(); 

These are the errors I recieve:

Uncaught TypeError: Cannot read property 'document' of undefined

Uncaught TypeError: Cannot read property 'readyState' of undefined

4
  • 3
    Cannot read property 'document' of undefined is pretty clear Commented Jul 3, 2012 at 18:56
  • 1
    iframe.contentWindow is not cross-browser? Commented Jul 3, 2012 at 19:00
  • 3
    On a side note: Say "No" to nested ternary operators. Commented Jul 3, 2012 at 19:02
  • I assume ifrm is a reference to an iframe node (like var ifrm = document.querySelector('iframe') for example). In that case you can have: ifrm.contentDocument or ifrm.contentWindow.document. Commented Jul 3, 2012 at 19:02

2 Answers 2

3

You are looking for the DOM element:

<iframe> 

iframe is the name of an HTML tag, not the value of the id of this element (which would be defined as id="value") so you want to use:

document.getElementsByTagName('iframe')[0] 

Change the 0 to whatever index is desired if there are multiple iframes on your page as getElementsByTagName() will return an array of results, even if there is only one iframe on the page.

Furthermore, you can simplify your ternary operation as follows:

ifrm = ifrm.contentWindow ? ifrm.contentWindow.document : ifrm.contentDocument; 

This way you can obtain the document object for the iframe in all browsers which will give you access to the open(), write(), and close() methods as well as the readyState attribute.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks... much good! try too use ID is best, parent.document.getElementById( XXXX ); not need [0] ;-)
Agreed. Using an ID is better as you can be more sure that you are retrieving the element you actually want.
2

put javascript source after tag.

like this

<html> <head> </head> <body> <iframe> <script> blah blah </script> </body> </html> 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.