ReferenceError: document is not defined (in plain JavaScript)

前端 未结 4 1999
遇见更好的自我
遇见更好的自我 2020-11-29 07:17

I get the a \"ReferenceError: document is not defined\" while trying to

var body = document.getElementsByTagName(\"body\")[0];

I have seen

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 07:59

    It depends on when the self executing anonymous function is running. It is possible that it is running before window.document is defined.

    In that case, try adding a listener

    window.addEventListener('load', yourFunction, false);
    // ..... or 
    window.addEventListener('DOMContentLoaded', yourFunction, false);
    
    yourFunction () {
      // some ocde
    
    }
    

    Update: (after the update of the question and inclusion of the code)

    Read the following about the issues in referencing DOM elements from a JavaScript inserted and run in head element:
    - “getElementsByTagName(…)[0]” is undefined?
    - Traversing the DOM

提交回复
热议问题