Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

202
Views
Javascript cannot read div from html

I have a javascript code which is connected to a htlm called "old.html". I do thing in there and then I have another html called "new.html" in which I want to add html elements in there.

I have this code in which I try to assign the div q1 to the variable myVar.

    var printWindow = window.open("http://10.180.101.58:5500/new.html", 'Print');
    var myVar = printWindow.document.getElementById('q1');

my html looks like this:

<body>

  <form>
    <div id="q1"></div>
  </form>

  <script src="DemoCode.js"></script>
</body>

These 2 files are in the same directory, but I think the problem is with the window.open()

I can't do document.getElementById() because I also have the "old.html" which let's say is the original html connected to my javascript and whenever I call document.getElementById() it gets elements from that one.

Does anyone know any way so that I can get elements from "new.html""?

I am using <script src="DemoCode.js"></script> in both html's so I can say that both are connected to my javaScript.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

There are two answers here:

  1. If the window where the code doing this is on the same origin (http://10.180.101.58:5500), you have to wait for the DOM to be loaded in the new window (for instance, using the DOMContentLoaded event) before you can access it.

  2. If the window where the code doing this isn't on the same origin as the new window you're opening, then you can't access its DOM, since of course that would be a massive security hole.

Here's how you'd do it in case #1:

const printWindow = window.open("http://10.180.101.58:5500/new.html", "Print");
printWindow.addEventListener("DOMContentLoaded", () => {
    const myVar = printWindow.document.getElementById("q1");
    // ...use it here...
});

I am using <script src="DemoCode.js"></script> in both html's so I can say that both are connected to my javaScript.

That doesn't in any way connect the windows (imagine all the windows that would be connected by jQuery or React loaded from a CDN!). All it does is load the code in that file into both windows.

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!