Executing JavaScript in the <head>, getElementById returns null

前端 未结 3 1195
旧巷少年郎
旧巷少年郎 2021-01-05 00:49

I have following code





        
相关标签:
3条回答
  • 2021-01-05 01:17

    It's null because you're calling the script before the DOM has been loaded.

    Wrap your script in a function which will be invoked onload, e.g.:

    window.onload = function() {
        var q = new foo();
        q.run('yellow');
    };
    
    0 讨论(0)
  • 2021-01-05 01:17

    This JS code will run before the DOM is ready so the node will not be found. To perform execution only once the DOM is ready, you could use the window.onload event handler.

    0 讨论(0)
  • 2021-01-05 01:37

    By the time the script is parsed, only the <html> and <head> tags have been loaded. There are several ways you can fix this:

    1. Put the <script> tags at the end of your document, instead of at the beginning
    2. Put the Javascript in another file and load it in the head with <script type="text/javascript" src="OtherFile.js"></script>
    3. Wrap the entire function in window.onload = function () { yourCodeHere(); }, which will halt execution of your code until the window has loaded.
    0 讨论(0)
提交回复
热议问题