Tengo un iframe y quiero agregarle un div usando JavaScript. Pero no aparece. ¿Qué estoy haciendo mal?
<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>Estoy ejecutando esto en mi servidor local usando la extensión de servidor en vivo VSCode y también lo ejecuté en el editor de prueba de w3schools:
¡Mira, no hay div rojo aquí!
Edición 1:
Bien, también verifiqué el DOM. Todavía nada aquí...
A Chrome le gusta un evento de carga; también podemos usar document.getElementById("zzz").contentDocument;
https://jsfiddle.net/mplungjan/ju8t6xoq/
Stacksnippets no permitirá acceder al 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); });