Accessing iframe body from parent

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Jezternz
    New Member
    • Jan 2008
    • 145

    Accessing iframe body from parent

    Simple enough, I want to access the body of an iframe from the parent window.
    The thing that makes this hard is I create the iframe dynamicly, aparently some of the methods I have been using only work when the frame is made when the document is loaded first.. Also note I need this to be able to run in FF and IE7

    Code:
    var board = document.createElement('iframe');	
    board.id = 'board';
    board.name = 'board';
    The following does not work (have looked over the net for a few things):

    Code:
    board.document.body.backgroundColor = red;
    board.contentWindow.document.body.backgroundColor = red;
    window.frames['board'].document.body.backgroundColor = red;
    Hopefully this is simple, thanks in advance, Josh
  • acoder
    Recognized Expert MVP
    • Nov 2006
    • 16032

    #2
    You can also use contentDocument where supported. To change the background, use style.backgroun dColor.

    Comment

    • Jezternz
      New Member
      • Jan 2008
      • 145

      #3
      oops, my bad, I meant to put the ".style" in.
      I tried using contentDocument it didnt seem to work.

      Code:
      var board = document.createElement('iframe');    
      board.id = 'board';
      board.name = 'board';
      document.body.appendChild(board);
      var thatiframe = board.contentDocument.body;
      I get the following error:
      Error 'board.contentD ocument.body' is null or not an object.

      Any ideas?

      By the way thanks alot acoder, you always seem to be very helpful, and go out of your way to help, cheers. Also thanks to the other experts.

      Comment

      • Jezternz
        New Member
        • Jan 2008
        • 145

        #4
        Simple Fix:

        Code:
        theiframebody = (iframe_el.contentDocument)?
         iframe_el.contentDocument.body:
          iframe_el.Document.body;
        You need to use 'Document' for IE :S

        thanks, Josh

        Comment

        • acoder
          Recognized Expert MVP
          • Nov 2006
          • 16032

          #5
          Hmm, that's strange. It should be contentWindow.d ocument for IE. However, I think I know what might be the cause. If you have this straight after appending, t may not be ready straight away (and hence undefined), so either use a timeout or call it iframe onload.

          Comment

          • Jezternz
            New Member
            • Jan 2008
            • 145

            #6
            ahhh that would make sence.
            cheers.

            Comment

            Working...