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.

This entry was posted in JavaScript, Web 2.0 and tagged , , , , , , , by Hazem Saleh. Bookmark the permalink.

About Hazem Saleh

Hazem Saleh has more than eleven years of experience in Cloud, Mobile and Open Source technologies. He worked as a software engineer, technical leader, application architect, and technical consultant for many clients around the world. He is an Apache PMC (Project Management Committee) member and a person who spent many years of his life writing open source software. Beside being the author of the "JavaScript Unit Testing" book, "JavaScript Mobile Application Development" book, "Pro JSF and HTML5" book and the co-author of the "Definitive guide to Apache MyFaces" book, Hazem is also an author of many technical articles, a developerWorks contributing author and a technical speaker in both local and international conferences such as ApacheCon North America, Geecon, JavaLand, JSFDays, CON-FESS Vienna and JavaOne. Hazem is an XIBMer, he worked in IBM for ten years. Now, He is working for Nickelodeon New York as a Mobile Architect. He is also an OpenGroup Master Certified Specialist.

One thought on “Accessing parent window elements from child window in JavaScript

  1. I’ve checked a hundred forums before finding this one. I wasted 4 hours on those sites.
    This is the ONLY correct answer to this question!
    Thanks like crazy.

Comments are closed.