Why is document.body null in my javascript?

前端 未结 6 2049
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-28 05:50

Here is my brief HTML document.

Why is Chrome Console noting this error:

\"Uncaught TypeError: Cannot call method \'appendChild\' of nul

6条回答
  •  旧时难觅i
    2020-11-28 06:34

    The body hasn't been defined at this point yet. In general, you want to create all elements before you execute javascript that uses these elements. In this case you have some javascript in the head section that uses body. Not cool.

    You want to wrap this code in a window.onload handler or place it after the tag (as mentioned by e-bacho 2.0).

    
        Javascript Tests
    
        
    
    

    See demo.

提交回复
热议问题