getElementById() returns null even though the element exists [duplicate]
You have to put this in a document
load
event. The DOM hasn't gotten to abc
by the time the script is executed.
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.
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>
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'));" >