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

泪湿孤枕 提交于 2019-12-01 09:21:30

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>

Just of note... Even after fixing the timing of it you can also have errors with this if you are developing on your local machine instead of on the internet or a local server. I just wasted an hour trying to figure out why it wouldn't work, then uploaded the same code to my server and it worked fine. I was using code that I ran locally 2 years ago but in a different browser, changed a few lines and the browser and it stopped working until running on a server. Hope this helps someone.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!