0

On running below code, getting following error - "Uncaught TypeError: Cannot set property 'onclick' of null"

<!DOCTYPE html>
<html>
<head>
<script>
document.getElementById("x").onclick = function() {
alert("clicked the button");
};
</script>
</head>
<body>
<button id="x">this is button</button>
</body>
</html>
arjit nair
  • 41
  • 1
  • 5

4 Answers4

2

You cannot get the element by id because the document is not loaded.

try to add onload function:

window.onload = function() {
  document.getElementById("x").onclick = function() {
    alert("clicked the button");
  };
};
kenticny
  • 437
  • 2
  • 7
  • 19
  • 1
    this solution is fine. But I have additional suggestion that you should put the after the

    element. Please google it you will find out why.

    – Kai Oct 04 '14 at 06:52
1

You're attempting to bind the click event before the button exists in the DOM. Either move your click event binding to the bottom of your body, of change it as follows:

<button id="x" onClick="alert('clicked the button');">this is button</button>

Cheers, autoboxer

autoboxer
  • 928
  • 9
  • 32
0

You need to set up an event listener:

var button = document.getElementById('x');

button.addEventListener('click', function() {
    console.log('button clicked');    
});
Sten Muchow
  • 6,373
  • 4
  • 33
  • 46
  • Uncaught TypeError: Cannot read property 'addEventListener' of null is the error being thrown. I am running the above code in w3school editor. – arjit nair Oct 04 '14 at 06:41
  • a... durp... indeed, your trying to get to the DOM before its ready. move your script out of the head and into the end of the body – Sten Muchow Oct 04 '14 at 06:43
0

You need to migrate your <script> element after <button>. The error is thrown because getElementById returns null as it could not find the element #x as the button#x element had not been yet reached at that point of time.

<!DOCTYPE html>
<html>
    <head>
    </head>
<body>
    <button id="x">this is button</button>
    <script>
       document.getElementById("x").onclick = function() {
           alert("clicked the button");
       };
    </script>
</body>
</html>
Gaurang Tandon
  • 5,704
  • 9
  • 37
  • 73
  • Its working! will accept your answer in a bit. Please explain how is it making a difference. Mine looks fine, right:? – arjit nair Oct 04 '14 at 06:43
  • Because the dom is not load ready when you get the element, so you cannot get the button dom in the script. The correct way is write script tag after the dom, or write the get element method in window.onload. – kenticny Jun 30 '17 at 10:58
  • @kenticny I think you were replying to the OP, in that case please use the `@` mention because instead I got notified :) – Gaurang Tandon Jun 30 '17 at 15:10