Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
503 views
in Technique[技术] by (71.8m points)

javascript - Getting document is not defined , from document.getElementById

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

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
</head>
<body>
    <h1>Hello Plunker!</h1>
    <button id="displayTodosButton">Display Todos</button>
    <button>Toggle Todos</button>
</body>
</html>

On my javascript file, I am simply trying to access the "Display todos" button using this:

var displayTodosButton = document.getElementById('displayTodosButton')

I was watching a video, and the instructor is using plnkr.co, and he accesses the button just fine, yet on Atom I get the "ReferenceError: document is not defined"

How can I fix this?

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 </body> tag. That way, any elements defined above them will have been created by the browser before your code runs.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...