PDA

View Full Version : Accessing the iFrame elements.


ali_ggl
02-06-2008, 12:49 PM
I am trying to access the content of my iframe src page. Something
like below

document.getElementById('myFrame').contentWindow.d ocument;

It works fine on a predifined iframe element, However, when creating
the iframe element
dynamically, and appending it to the body, I can't access the content
when doing this dynamic insertion. My guess would be that this is
because the iframe element doesn't yet exist on the Dom. See example
of problem below:

var myFrame = document.createElement("iframe");
myFrame.id = "testID";
myFrame.name = "testID";
myFrame.src = "testPage.htm";
myFrame.frameBorder = "0";

document.body.appendChild(myFrame);

//code below isn't working due to the above
document.getElementById('testID').contentWindow.do cument;

Does anyone have any example to access the elements of iFrame or Frame in browser
so I can do to resolve this issue?

Thanks
Ali

ASWC
02-06-2008, 02:24 PM
You can still access it by code just store its ID in a global variable in your Javascript then you'll be able to work with it using the global variable.

jsebrech
02-06-2008, 03:23 PM
Maybe you think this is a silly question, but are you accessing the contentWindow variable of your newly added iframe immediately after calling appendChild, or are you waiting until the onload event for the iframe is triggered? I'm asking this because iframes load asynchronously, and so contentWindow.document won't be immediately available after adding it to the body.