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

242
Views
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 answers
Answer question

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 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!