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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With