简体   繁体   中英

Cannot call method 'appendChild' of null for iframes

I have the following script to create an iframe

  function createIframe() {
    var iframe = document.createElement("iframe");
    iframe.style.position = "absolute";
    iframe.style.visibility = "hidden";

    document.body.appendChild(iframe);

    // Firefox, Opera
    if(iframe.contentDocument) iframe.doc = iframe.contentDocument;
    // Internet Explorer
    else if(iframe.contentWindow) iframe.doc = iframe.contentWindow.document;

    // Magic: Force creation of the body (which is null by default in IE).
    // Also force the styles of visited/not-visted links.
    iframe.doc.open();
    iframe.doc.write('<style>');
    iframe.doc.write("a{color: #000000; display:none;}");   
    iframe.doc.write("a:visited {color: #FF0000; display:inline;}");    
    iframe.doc.write('</style>');
    iframe.doc.close();

    // Return the iframe: iframe.doc contains the iframe.
    return iframe;
  }  

however in chrome console it is giving me the error Cannot call method 'appendChild' of null

why is it not working?

The code is correct. Have you added body in the page?

Try this:

<html>
<body>
<script>
window.onload=function() {
   createIframe()
};
function createIframe() {
    var iframe = document.createElement("iframe");
    iframe.style.position = "absolute";
    iframe.style.visibility = "hidden";

    document.body.appendChild(iframe);

    // Firefox, Opera
    if(iframe.contentDocument) iframe.doc = iframe.contentDocument;
    // Internet Explorer
    else if(iframe.contentWindow) iframe.doc = iframe.contentWindow.document;

    // Magic: Force creation of the body (which is null by default in IE).
    // Also force the styles of visited/not-visted links.
    iframe.doc.open();
    iframe.doc.write('<style>');
    iframe.doc.write("a{color: #000000; display:none;}");   
    iframe.doc.write("a:visited {color: #FF0000; display:inline;}");    
    iframe.doc.write('</style>');
    iframe.doc.close();

    // Return the iframe: iframe.doc contains the iframe.
    return iframe;
  }  
</script>
</body>
</html>

iframe.doc.write is not the cleanest solution....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM