Friday 31 July 2009

Access DOM Element Within IFrame

Suppose we have a html page with frame or iframe in it and we need to get an element in it. Simple

document.getElementById("myElement");

will not find it, as it is searched only in the main page, where the frame is set. What we should do, is to find the frame first and then look for needed element in the right frame.

frame = document.getElementById("myFrame"); 
frame.contentWindow.getElementById("myElement");

2 comments:

  1. http://xkr.us/articles/dom/iframe-document/
    :
    Browser Disagreements
    contentWindow vs. contentDocument

    IE (Win) and Mozilla (1.7) will return the window object inside the iframe with oIFrame.contentWindow.
    Safari (1.2.4) doesn't understand that property, but does have oIframe.contentDocument, which points to the document object inside the iframe.
    To make it even more complicated, Opera 7 uses oIframe.contentDocument, but it points to the window object of the iframe.

    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.

    ReplyDelete
  2. Thanks for pointing out. I have tested that only in FF and IE :) That's why it worked for me.

    ReplyDelete