Christian Heinrichs Christian Heinrichs - 1 month ago 7
CSS Question

Accessing HTML elements inside frames from parent document

How can I access HTML elements contained in a frame from the parent document?

I have tried window.frames, contentWindow and parent.frames, but I get all kinds of errors.

Here is the code of the parent HTML file:

<html>
<head>
<title>Parent HTML file</title>
<script type="text/javascript">
alert(window.frames["frame1"].window.getElementsByTagName("input")[0].value);
alert(document.getElementsByName("frame1").contentWindow);
alert(parent.frames[0]document.getElementsByTagName("input")[0].value);
</script>
</head>
<frameset cols="50%,50%">
<frame src="frame1.html" name="frame1">
<frame src="frame2.html" name="frame2">
<noframes>
<body>
<p>Text</p>
</body>
</noframes>
</frameset>
</html>

Answer

frames collection or any inputs don't exist at the time you try to refer them. You can try this:

window.onload = function () {
    alert(window.frames["frame1"].document.getElementsByTagName("input")[0].value;
}

Notice, that frames collection contains window objects instead of frame/iframe elements.

Comments