简体   繁体   English

JavaScript通过ID获取元素

[英]Javascript get element by id

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 msg is null. 它返回一条错误msg指出msg为空。 What should I do? 我该怎么办?

Firstly, you have to consider that JavaScript is case sensitive language, so you should use getElementById (note case of last letter). 首先,您必须考虑JavaScript是区分大小写的语言,因此您应该使用getElementById (注意最后一个字母的大小写)。 Next, if you get element by id, you should pass ID as an argument (not a tag name): 接下来,如果您通过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, ie when your msg element is "visible" for JavaScript. 另外,一个重要的注意事项是在标记完全加载后,即当msg元素对于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> . 为此,一种选择是将<script>标记(带有相应的JavaScript代码)放在</body>之前的HTML末尾。

In the head section I then have: 然后在头部分中有:

 var msg = document.getElementByID("div"); 

Three issues there: 那里的三个问题:

  1. If that code is in head , but the element is defined in body , the element doesn't exist yet when the code is run. 如果该代码在head ,但该元素在body定义,则在代码运行时该元素尚不存在。

  2. The element's id is "msg" , not div . 元素的id"msg" ,而不是div div is its tag name, and isn't unique. div是其标签名称,并非唯一。

  3. It's getElementById , not getElementByID . 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") ,那应该没问题。

Because you are calling it before the page has loaded the element. 因为您是在页面加载元素之前调用它。 You need to wait for document ready or window.onload to reference the element. 您需要等待文档准备就绪window.onload才能引用该元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM