9

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.

joragupra
  • 692
  • 1
  • 12
  • 23
lunar
  • 1,122
  • 5
  • 18
  • 28

2 Answers2

17

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.

TimWolla
  • 28,958
  • 8
  • 59
  • 84
2

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.

ziesemer
  • 26,239
  • 8
  • 80
  • 90