Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

205
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda