How to set innerHTML of any element in a window opened by a JavaScript window object?

I have a simple JavaScript code:

<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 the onclick event. The window opens fine, but the innerHTML element does not change. This is the file that I have, so I know that I am not blocked by any security policy, and the element with id 'foo' definitely exists. (This is a DIV). I tried other .innerHTML options like .src and .value but nothing works. Anyone have any suggestions?

+3
source share
2 answers

The problem is that you are most likely trying to access the DOM of a new window before that window can complete the download.

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 DOM only after it onload event fires.
     mywindow.onload = function() {
         mywindow.document.getElementById("foo").innerHTML="Hey you!!";
     }

   }
</script>
+8
source

... , , . , , , , . , 2 , , , , . , -.

0

All Articles