Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>

like image 714
Softnux Avatar asked Mar 20 '11 19:03

Softnux


People also ask

Why is my document getElementById returning NULL?

This error TypeError: document. getelementbyid(...) is null would seem to indicate that there is no such element with an ID passed to getElementById() exist. This can happen if the JavaScript code is executed before the page is fully loaded, so its not able to find the element.

How do I fix document getElementById?

To solve the "getElementById is not a function" error, make sure to spell the getElementById() method correctly, as it is case-sensitive, and only call the method on the document object, e.g. document. getElementById('btn') . Copied! Now we are able to call the getElementById method on the document object.

What does the document getElementById () method return?

The Document method getElementById() returns an Element object representing the element whose id property matches the specified string. Since element IDs are required to be unique if specified, they're a useful way to get access to a specific element quickly.


2 Answers

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

like image 78
Daniel A. White Avatar answered Oct 02 '22 17:10

Daniel A. White


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.

like image 50
mVChr Avatar answered Oct 02 '22 17:10

mVChr