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

删除回忆录丶 提交于 2019-11-26 02:11:28

问题


This question already has an answer here:

  • Why does jQuery or a DOM method such as getElementById not find the element? 8 answers

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>


回答1:


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




回答2:


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.




回答3:


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>



回答4:


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'));" >



回答5:


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.



来源:https://stackoverflow.com/questions/5371047/getelementbyid-returns-null-even-though-the-element-exists

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