This question already has answers here:
Closed 5 years ago.
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.
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.
Because the element doesn't yet exist when the script runs - the document hasn't been rendered yet. Either run the script in a script block after the related HTML, or use a "document on ready" event handler - preferably from something like jQuery's .ready()
event, or the native window.onload
.