getElementById() returns null even though the element exists
JavascriptHtmlNullGetelementbyidJavascript Problem Overview
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>
Javascript Solutions
Solution 1 - Javascript
You have to put this in a document
load
event. The DOM hasn't gotten to abc
by the time the script is executed.
Solution 2 - Javascript
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.
Solution 3 - Javascript
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>
Solution 4 - Javascript
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'));" >
Solution 5 - Javascript
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.