How to set the innerHTML of some element in a window opened by a JavaScript window object?
html, javascript, window.open
Solution
The problem here is that you are most likely trying to access the DOM of the new window before that window has a chance to finish loading.
Consider the following:
<script type="text/javascript">
function openWindow() {
var mywindow = window.open("file.html");
// register an onload event with the popup window so that we attempt to
// modify it's DOM only after it's onload event fires.
mywindow.onload = function() {
mywindow.document.getElementById("foo").innerHTML="Hey you!!";
}
}
</script>
Problem
I have some simple JavaScript code like this: ``` <script type="text/javascript"> function openWindow() { var mywindow = window.open("file.html"); mywindow.document.getElementById("foo").innerHTML="Hey you!!"; } </script> ``` This function is called with an onclick event. The window opens fine, but the element's innerHTML does not change. It is a file I own, so I know I am not being blocked by any security policy, and the element with id 'foo' definitely exists. (It is a DIV). I have tried other variations of .innerHTML like .src and .value, but nothing seems to work. Does anyone have any suggestions?