1

I want to open an html file with JavaScript and write some data into some of its elements. I tried the following:

var info_window = window.open('info_print.html')
info_window.document.getElementById('new_info').innerHTML = data;

But I get this error while I have the #new_info element:

cannot set property 'innerHTML' of null

what should I do? I checked the commented question but it was not as my question.

Nawras
  • 181
  • 1
  • 12
  • 1
    Looks like there's no element with `id` equal to `new_info` in the new window. You're probably either searching for the wrong element or (more likely) not waiting enough time for the window to load the element you want. – Marco Bonelli Nov 15 '18 at 12:22
  • 7
    Possible duplicate of [Add content to a new open window](https://stackoverflow.com/questions/10472927/add-content-to-a-new-open-window) – richflow Nov 15 '18 at 12:22
  • @richflow Not really a duplicate of that! The other question is asking for a totally different thing, and the suggested answers don't take into consideration the loading time of the window, since the other question's OP didn't need to. This is a totally different situation! – Marco Bonelli Nov 15 '18 at 12:31
  • @MarcoBonelli my bad! please let me know what I should do to correct this. – richflow Nov 17 '18 at 06:53
  • @richflow well you can retract the close vote if you want, just click on "close" again and a menu will pop up – Marco Bonelli Nov 17 '18 at 10:47

2 Answers2

1

Assuming your info_print.html actually contains the element you're looking for, then you need to wait for the Window to load it before accessing it.

Here's a simple solution using the onload event:

var info_window = window.open('info_print.html');

info_window.addEventListener('load', function() {
    info_window.document.getElementById('new_info').innerHTML = data;
});
Marco Bonelli
  • 63,369
  • 21
  • 118
  • 128
1

I have created one fiddle where it is working fine. can you please check if your html file contains new_info element or not or if you are getting any errors in console.

below is my fiddle code.

var w = window.open('', "", "width=600, height=400, scrollbars=yes");
//assuming html as your info_print.html file which contains new_info element
var html = '<div id="new_info"></div>';
w.document.body.innerHTML = html;
w.document.getElementById("new_info").innerHTML="test content";
Dhaval Pankhaniya
  • 1,996
  • 1
  • 15
  • 26