即使元素存在,getElementById()也会返回null

即使元素存在,getElementById()也会返回null

问题描述:

我试图用getElementById()获取元素,但即使元素存在,它也会返回null。我做错了什么?

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>


你必须把它放在文档 load 事件中。在执行脚本时,DOM没有得到 abc

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