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

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>

Answers:

Answer

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

Answer

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.

Answer

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.

Answer

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>
Answer

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

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.