document.body.appendChild(i)

后端 未结 6 1280
傲寒
傲寒 2020-12-08 19:50

I am getting error only in IE7 as document.body is null; when I debug with Microsoft script editor I am getting the error in the following line: i.e.

相关标签:
6条回答
  • 2020-12-08 20:08

    May also want to use "documentElement":

    var elem = document.createElement("div");
    elem.style = "width:100px;height:100px;position:relative;background:#FF0000;";
    document.documentElement.appendChild(elem);
    
    0 讨论(0)
  • 2020-12-08 20:18

    You can appendChild to document.body but not if the document hasn't been loaded. So you should put everything in:

    window.onload=function(){
        //your code
    }
    

    This works or you can make appendChild to be dependent on something else like another event for eg.

    https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_doc_body_append

    As a matter of fact you can try changing the innerHTML of the document.body it works...!

    0 讨论(0)
  • 2020-12-08 20:19

    If your script is inside head tag in html file, try to put it inside body tag. CreateElement while script is inside head tag will give you a null warning

    <head>
      <title></title>
    </head>
    
    <body>
      <h1>Game</h1>
      <script type="text/javascript" src="script.js"></script>
    </body>
    
    0 讨论(0)
  • 2020-12-08 20:22

    It is working. Just modify to null check:

    if(document.body != null){
        document.body.appendChild(element);
    }
    

    Pointy's suggestion is good; it may work, but I didn't try.

    0 讨论(0)
  • 2020-12-08 20:23

    In 2019 you can use querySelector for that.

    It's supported by most browsers (https://caniuse.com/#search=querySelector)

    document.querySelector('body').appendChild(i);
    
    0 讨论(0)
  • 2020-12-08 20:24

    You could try

    document.getElementsByTagName('body')[0].appendChild(i);
    

    Now that won't do you any good if the code is running in the <head>, and running before the <body> has even been seen by the browser. If you don't want to mess with "onload" handlers, try moving your <script> block to the very end of the document instead of the <head>.

    0 讨论(0)
提交回复
热议问题