Javascript Javascript通过id获取元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13712984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript get element by id
提问by MrD
My HTML includes the code:
我的 HTML 包含以下代码:
<div id="msg"></div>
In its body.
在它的体内。
In the head section I then have:
在头部部分,我有:
var msg = document.getElementByID("msg");
But when I then call within a function:
但是当我在一个函数中调用时:
msg.innerHTML = "test";
It returns an error stating that msgis null. What should I do?
它返回一个错误,指出它msg为空。我该怎么办?
回答by VisioN
Firstly, you have to consider that JavaScript is case sensitive language, so you should use getElementById(note case of last letter). Next, if you get element by id, you should pass ID as an argument (not a tag name):
首先,您必须考虑 JavaScript 是区分大小写的语言,因此您应该使用getElementById(注意最后一个字母的大小写)。接下来,如果您通过 id 获取元素,则应将 ID 作为参数(而不是标签名称)传递:
var msg = document.getElementById("msg");
You can read more information about this method in MDN:
您可以在MDN 中阅读有关此方法的更多信息:
Also, one important note is to use this code when the markup is fully loaded, i.e. when your msgelement is "visible"for JavaScript. In order to achieve this, one option is to put your <script>tag (with corresponding JavaScript code) to the end of HTML right before </body>.
此外,一个重要的注意事项是在标记完全加载时使用此代码,即当您的msg元素对 JavaScript “可见”时。为了实现这一点,一种选择是将您的<script>标签(带有相应的 JavaScript 代码)放在 HTML 的末尾</body>.
回答by T.J. Crowder
In the head section I then have:
var msg = document.getElementByID("div");
在头部部分,我有:
var msg = document.getElementByID("div");
Three issues there:
那里的三个问题:
If that code is in
head, but the element is defined inbody, the element doesn't exist yet when the code is run.The element's
idis"msg", notdiv.divis its tag name, and isn't unique.It's
getElementById, notgetElementByID.
如果该代码在 中
head,但元素在 中定义body,则在运行代码时该元素尚不存在。元素的
id是"msg",不是div。div是它的标签名称,并且不是唯一的。是
getElementById,不是getElementByID。
If you move your script element containing the code to just before the closing </body>tag on your page, and use document.getElementById("msg"), you should be fine.
如果您将包含代码的脚本元素移动到</body>页面上的结束标记之前,并使用document.getElementById("msg"),则应该没问题。
回答by epascarello
Because you are calling it before the page has loaded the element. You need to wait for document readyor window.onloadto reference the element.
因为您在页面加载元素之前调用它。您需要等待文档就绪或window.onload来引用该元素。

