This example shows how to use JavaScript to access parent elements from within a child, and vice versa. I'll demonstrate how to get or set a value in the child, from the parent, or in the parent, from the child. The trick is getting a reference to the target container, and then knowing enough about the DOM in that target to access the specific element you are after. While this example uses an IFRAME, the mechanism, and rules apply to child windows and frames as well, though getting the attachment to the target "window" object may require some tweaking. (If you have a specific example this doesn't work for, please share, I'll see if I can suggest a method. Thanks.)
The example shows a form in this page (which is the parent in our example.) Two IFRAMEs load the same page from different URLs. The first IFRAME's child page comes from another page on this domain. It's JavaScript can then access elements in this page for reading or writing. The second IFRAME child comes from a different domain. While the page is the same, because of a cross-domain scripting security rule in JavaScript, that child cannot read or write to DOM elements in the parent (this page).
| (IFRAME container) |
| (IFRAME container) |
Note: There is a cross-domain scripting security rule that can become an issue in these scenarios. When a child container (IFRAME in this case) has JavaScript from a page within the same domain as the parent, that child can access elements within the parents document object model (DOM). But when the child is from a different domain, the child can no longer access the parent's internals, nor can the parent access the child's internal elements.
Note: Uncontrolled JavaScript Errors - If you are new to JavaScript, when you attempt an operation which results in an error, that error is returned to your browser. For Internet Explorer you'll see an error icon appear at the bottom of your browser. If you want to see the details of the error, you need to double-click that icon to display the details. If you are using Firefox, you'll need to type "javascript:" in the address in order to pop open the console where you can view the error. I'm not sure how to do this on a Mac, or Linux, or other browsers. (I'd love input if anyone wants to share. Thanks.) In this example, I've defaulted the operations to go through the JavaScript TRY and CATCH error handlers. This means by default, operations that result in an error should be handled in a controlled manner, and instead of seeing nothing, you'll see an alert which indicates an error happened.
Author: Thomas Ballard.