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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 16:54:41  来源:igfitidea点击:

getElementById() returns null even though the element exists

javascripthtmlnullgetelementbyid

提问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 documentloadevent. The DOM hasn't gotten to abcby the time the script is executed.

你必须把它放在一个documentload事件中。到abc脚本执行时,DOM 还没有达到。

回答by mVChr

Your script runs before the DOM has been loaded. To fix this you can place your code in the window.onloadfunction like so:

您的脚本在 DOM 加载之前运行。要解决此问题,您可以将代码放在window.onload函数中,如下所示:

window.onload = function() {
    alert(document.getElementById("abc"));
};

An alternative is to place your scriptright 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 事件。