即使元素存在,getElementById() 也会返回 null
我尝试使用 getElementById() 获取元素,但即使该元素存在,它也会返回 null。我做错了什么?
<html>
<head>
<title>blah</title>
<script type="text/javascript">
alert(document.getElementById("abc"));
</script>
</head>
<body>
<div id="abc">
</div>
</body>
I'm trying to get the element with getElementById(), but it returns null even though the element exists. What am I doing wrong?
<html>
<head>
<title>blah</title>
<script type="text/javascript">
alert(document.getElementById("abc"));
</script>
</head>
<body>
<div id="abc">
</div>
</body>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您必须将其放入
document
load
事件中。执行脚本时,DOM 尚未到达abc
。You have to put this in a
document
load
event. The DOM hasn't gotten toabc
by the time the script is executed.您的脚本在 DOM 加载之前运行。要解决此问题,您可以将代码放置在
window.onload
函数中,如下所示:另一种方法是将您的
script
放置在结束之前。
标签。Your script runs before the DOM has been loaded. To fix this you can place your code in the
window.onload
function like so:An alternative is to place your
script
right before the closing</body>
tag.如果您不想附加到加载事件,则只需将脚本放在正文的底部,这样它将在最后执行 -
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-
这是因为脚本在页面呈现之前运行。
为了证明这一点,请将此属性添加到 body 标记中:
This is because the script runs before the page has rendered.
For proof add this attribute to the body tag:
但它并不存在,在 HTML 中不存在。 HTML 文档是从上到下解析的,就像程序运行一样。最好的解决方案是将脚本标签放在页面底部。您还可以将 JavaScript 附加到 onload 事件。
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.