views:

170

answers:

4

In the following code, the alert works fine and prints "DIV : IFRAME" as it should however it then says that cNs[1].childNodes[1].document has no properties.

Html:

<div id="WinContainer">
 <div style="display: none;"><iframe id="frame1" name="frame1"></iframe></div>
 <div style="display: none;"><iframe id="frame2" name="frame2"></iframe></div>
</div>

JavaScript:

var cNs = document.getElementById('WinContainer').childNodes;
alert(cNs[1].tagName + ' : ' + cNs[1].childNodes[1].tagName);
cNs[1].childNodes[1].document.location = 'someurl.pl';

BUT if I do this:

frame1.document.location = 'someurl.pl';

it works fine.

+2  A: 

The iframe DOM node has a property called contentDocument which will be the equivalent of document, but for that iframe.

If the page being displayed is on another server tho (or even on a different port on the same server) you will get a security exception trying to access it.

Not sure if this works for IE.

David Hedlund
why does frame1.document.location work fine then?
frame1.document.location works because you are changing the frame's location without being able to read anything from it. For example, you could have a large iframe which loaded either Facebook or Myspace when you clicked a button, but the javascript may not have access to the contents of either, because it could steal your personal data.
Phil H
contentDocument is also null
A: 

I'm not all that familiar with javascript but it looks like you're using cNs incorrectly. It looks as though it is an array containing the child nodes and the code

cNs[1].childNodes[1].document.location = 'someurl.pl';

is trying to get the child nodes that do not exist. Try this it might work.

cNs[1].document.location = 'someurl.pl';
ChadNC
A: 

EDIT: frame1 should be:

cNs[0].childNodes[0].document.location

Remember that things are 0 indexed.

md5sum
in IE this works, in firefox my elements are indexed at 1,1 not 0,0
Check out http://www.quirksmode.org/js/detect.html for a quick tutorial on browser detection if things are being indexed differently.
md5sum
A: 

You can also reference the reliable contentWindow property to get to that iFrame's document object as such:

cNs[0].childNodes[0].contentWindow.document
Justin Swartsel