getElementById() returns null even though the element exists

Softnux picture Softnux · Mar 20, 2011 · Viewed 96.5k times · Source

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>

Answer

Daniel A. White picture Daniel A. White · Mar 20, 2011

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