I know this is a little late, but I studied this and came across your question:
I got the same error as you, because the div I was trying to add iframe to was not loaded yet, when I was trying to add iframe. If the div is loaded, your code works:
<!DOCTYPE html> <html> <head> </head> <body> <div id='test' > </div> <script> var iframe = document.createElement('iframe'); var myDiv = document.getElementById('test'); myDiv.appendChild(iframe); if (iframe.contentDocument) { iframe.contentDocument.write("Hello"); } else if (iframe.contentWindow) { iframe.contentWindow.document.body.innerHTML = "Hello"; } </script> </body> </html>
Here is a jsFiddle with this working code and another with a tag when TypeError: Cannot call method 'appendChild' of null error TypeError: Cannot call method 'appendChild' of null .
source share