Search code examples
javascripthtmliframe

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


Solution

  • 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);
    });