Accessing parent window elements from child window in JavaScript

In JavaScript you can access the parent window elements from the child window. Let’s see an example. Let’s assume that the parent page code is as follows:

<html>
    <head>
        <title>Parent Window</title>
    </head>
    <body>   
	<input type="text" id="data" value="23444" />
	<a href="#" onclick="javascript:openChildWindow();">Open Child Popup window</a>
    </body>
    <script>
	function openChildWindow() {
		window.open('child.htm','childWindow','width=400,height=400');		
	}
    </script>
</html>

The hyperlink in the parent window opens a new child window using the window.open JavaScript API.

In the child window, Let’s see how to access the "data" input field of the parent window.

<html>
    <head>
        <title>Child Window</title>
    </head>
    <body onload="initializeMainDiv();">   
		<div id="mainDiv"></div>
    </body>
    <script>
	function initializeMainDiv() {
		document.getElementById("mainDiv").innerHTML = "Parent window data field value is: " + 
			window.opener.document.getElementById("data").value
	}
    </script>
</html>

In the child window, when the page is initialized, the "data" input field of the parent window is accessed through the window.opener JavaScript API.