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

247
Vistas
Unable to create a div inside iframe

I have an iframe and I want to add a div to it using JavaScript. But it's not showing up. What am I doing wrong?

<html>
  <body>

      <iframe
        id="zzz"
        srcdoc="<html><h1>hello</h1><button>click </button> <button>btn 2</button></html>"
        width="500"
        height="500">
      </iframe>

    <script>
      let myiframe = document.getElementById("zzz").contentWindow.document;
      let mydiv = myiframe.createElement("div");
      mydiv.style.background = "red";
      mydiv.style.width = "300px";

      myiframe.body.appendChild(mydiv);
    </script>

  </body>
</html>

I'm running this on my local server using VSCode live server extension and I also ran it on w3schools tryit editor too:

enter image description here

See, no red div here!

Edit 1:

Okay, I checked the DOM too. Still nothing here...

enter image description here

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Chrome likes a load event - also we can use document.getElementById("zzz").contentDocument;

https://jsfiddle.net/mplungjan/ju8t6xoq/

Stacksnippets will not allow accessing the iFrame

window.addEventListener("load", function() {
  let myiframeDocument = document.getElementById("zzz").contentDocument;
  let mydiv = myiframeDocument.createElement("div");
  mydiv.style.background = "red";
  mydiv.style.width = "300px";
  mydiv.style.height = "300px";
  mydiv.textContent = 'bla'

  myiframeDocument.body.appendChild(mydiv);
});
about 4 years ago · Juan Pablo Isaza 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