61

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>

Deduplicator
  • 41,806
  • 6
  • 61
  • 104
Softnux
  • 1,930
  • 4
  • 17
  • 20

5 Answers5

84

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

Daniel A. White
  • 174,715
  • 42
  • 343
  • 413
47

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.

mVChr
  • 46,510
  • 10
  • 101
  • 99
  • 5
    "Right before /BODY" may confuse beginners. The requirement is to place the SCRIPT after the HTML element that the script needs to reference. The distance to /BODY is not relevant. – Šime Vidas Mar 20 '11 at 20:02
  • 1
    another thing to note. If you have a window.onload that follows another window onload **from top-to-bottom on the document**, the second window onload will override the content of the first window.onload. For example, if you tried setting a **
    s** background color inside the first window.onload using a JS handle like so: `document.getElementById('div01').style.background = 'blue';` and had the same handle inside the second window.onload but set to 'black', your div's background color would be black not blue. Order in the DOM matters.
    – LVX-001 Nov 17 '19 at 20:54
  • Great answer! Simple and including the working example! – The_Long_Distance_Runner Feb 09 '21 at 16:52
11

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>
Premraj
  • 7,462
  • 8
  • 43
  • 65
4

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'));" >
Hogan
  • 63,843
  • 10
  • 75
  • 106
1

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.

jpsimons
  • 24,016
  • 3
  • 31
  • 45