Getting document is not defined , from document.getElementById

后端 未结 3 630
一生所求
一生所求 2020-12-10 23:09

I am learning JavaScript and I am using Atom (Text Editor). On my HTML file I got only this:




    

        
3条回答
  •  天涯浪人
    2020-12-10 23:56

    yet on Atom I get

    If you really mean that Atom, your text editor, is highlighting it and showing you a warning that document is undefined, it's just that Atom doesn't realize you're running that code in a browser context where document will be defined.

    It probably has a setting where you can tell it that you'll be running the code in a browser, so it can assume the default set of globals (window, document, etc.).


    If the code in script.js is just what you've shown, although the error Atom is showing you won't be a problem (because in the browser, document will not be undefined), you'll get null back from getElementById because your code runs before the element exists. Again, this is assuming that code is on its own, not (say) inside a DOMContentLoaded handler or similar.

    Unless you have a good reason to do it (and there aren't many), putting script elements in the head is an anti-pattern. Put them in body, right at the end, just prior to the closing tag. That way, any elements defined above them will have been created by the browser before your code runs.

提交回复
热议问题