Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getElementById and null - why? [duplicate]

Why doesn't this code work? I'am using FF.

<head>
<script type="text/javascript">

document.getElementById("someID").onclick = function(){
    alert("Yahooo");
}
</script> 
</head>

<body> 
<a href="#" id="someID">someID</a>
</body>

</html>

I'm getting javascript error getElementById equals to null.

like image 209
lunar Avatar asked Jan 14 '12 19:01

lunar


People also ask

Why is my 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.

What will method getElementById () return if nothing is found?

The getElementById() method returns an element with a specified value. The getElementById() method returns null if the element does not exist. The getElementById() method is one of the most common methods in the HTML DOM.

What is difference between getElementById and getElementsByClassName?

getElementById returns a single DOM element whose ID matches your query. getElementsByClassName returns an HtmlCollection - an array-like structure containing the DOM elements that matched your query. You have to iterate through each element in the array to apply your style.


1 Answers

The needed DOM is not loaded when the script is executed. Either move it down (below the href) or define it like this:

window.onload = function () {
    document.getElementById("someID").onclick = function(){
        alert("Yahooo");
    }
}

window.onload will be called when the page is completely loaded.

like image 115
TimWolla Avatar answered Sep 23 '22 07:09

TimWolla