Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

244
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda