Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

See, no red div here!

Edit 1:

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

enter image description here

>Solution :

Chrome likes a load event – also you can just use document.createElement

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

Stacksnippets will not allow accessing the iFrame

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

  myiframe.body.appendChild(mydiv);
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading