getElementById() returns null even though the element exists [duplicate]

本秂侑毒 提交于 2019-11-26 10:35:03

You have to put this in a document load event. The DOM hasn't gotten to abc by the time the script is executed.

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

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

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-

<html>
<head> 
    <title>blah</title>    
</head> 
<body>
    <div id="abc">
    </div>
    <script type="text/javascript">
        alert(document.getElementById("abc"));
    </script>
</body>
</html>

This is because the script runs before the page has rendered.

For proof add this attribute to the body tag:

<body onload="alert(document.getElementById('abc'));" >

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!