Javascript 即使元素存在 getElementById() 也返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5371047/
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
getElementById() returns null even though the element exists
提问by Softnux
I'm trying to get the element with getElementById(), but it returns null even though the element exists. What am I doing wrong?
我正在尝试使用 getElementById() 获取元素,但即使该元素存在,它也会返回 null。我究竟做错了什么?
<html>
<head>
<title>blah</title>
<script type="text/javascript">
alert(document.getElementById("abc"));
</script>
</head>
<body>
<div id="abc">
</div>
</body>
回答by Daniel A. White
You have to put this in a document
load
event. The DOM hasn't gotten to abc
by the time the script is executed.
你必须把它放在一个document
load
事件中。到abc
脚本执行时,DOM 还没有达到。
回答by mVChr
Your script runs before the DOM has been loaded. To fix this you can place your code in the window.onload
function like so:
您的脚本在 DOM 加载之前运行。要解决此问题,您可以将代码放在window.onload
函数中,如下所示:
window.onload = function() {
alert(document.getElementById("abc"));
};
An alternative is to place your script
right before the closing </body>
tag.
另一种方法是将您的script
权利放在结束</body>
标记之前。
回答by Premraj
If you don't want to attach to the load event then simply put your script at the bottom of the body, so it will execute at the end-
如果您不想附加到加载事件,那么只需将您的脚本放在正文的底部,这样它就会在最后执行-
<html>
<head>
<title>blah</title>
</head>
<body>
<div id="abc">
</div>
<script type="text/javascript">
alert(document.getElementById("abc"));
</script>
</body>
</html>
回答by Hogan
This is because the script runs before the page has rendered.
这是因为脚本在页面呈现之前运行。
For proof add this attribute to the body tag:
为了证明,将此属性添加到 body 标记中:
<body onload="alert(document.getElementById('abc'));" >
回答by jpsimons
But it doesn't exist, not at that point in the HTML. HTML documents are parsed top-to-bottom, just like programs run. The best solution is just to put your script tag at the bottom of the page. You could also attach your JavaScript to the onload event.
但它不存在,在 HTML 中不存在。HTML 文档是从上到下解析的,就像程序运行一样。最好的解决方案是将您的脚本标签放在页面底部。您还可以将 JavaScript 附加到 onload 事件。