Solve - Cannot set property 'onclick' of Null in JS

ยท

2 min read

The "Cannot set property 'onclick' of null" error occurs for 2 reasons:

  1. Setting the onclick property on a null value (DOM element that doesn't exist).
  2. Placing the JS script tag above the HTML where the DOM elements are declared.

image.png

Here is an example of how the error occurs.

const button = null;

// โŒ Cannot set properties of null (setting 'onclick')
button.onclick = function click() {
  console.log('Button clicked');
};

To solve the "Cannot set property 'onclick' of null" error, make sure the id you're using to access the element exists in the DOM. The error often occurs after providing a non-existent id to the getElementById method.

const button = document.getElementById('does-not-exist');
console.log(button); // ๐Ÿ‘‰๏ธ null

// โŒ Cannot set properties of null (setting 'onclick')
button.onclick = function click() {
  console.log('Button clicked');
};

We passed a non-existent id to the getElementById method and got a null value back. Setting the onclick property on a null value causes the error.

To solve the "Cannot set property 'onclick' of null" error, place the JS script tag at the bottom of the body tag. The script should run after the DOM elements have been created.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <!-- โ›”๏ธ BAD - script is ran before button exists โ›”๏ธ -->
    <script src="index.js"></script>

    <button id="btn">Click me</button>
  </body>
</html>

We placed the JS script tag above the code that creates the button element. This means that the index.js file is ran before the button is created, therefore we don't have access to the button element in the index.js file.


const button = document.getElementById('btn');
console.log(button); // ๐Ÿ‘‰๏ธ null

// โŒ Cannot set properties of null (setting 'onclick')
button.onclick = function click() {
  console.log('Button clicked');
};

The JS script tag should be moved to the bottom of the body, after all of the DOM elements it needs access to.

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
  </head>
  <body>
    <button id="btn">Click me</button>

    <!-- โœ… GOOD - button already exists โœ… -->
    <script src="index.js"></script>
  </body>
</html>

Now, the index.js file has access to the button element.


const button = document.getElementById('btn');
console.log(button); // ๐Ÿ‘‰๏ธ button#btn

// โœ… Works
button.onclick = function click() {
  console.log('Button clicked');
};

The "Cannot set property 'onclick' of null" error occurs when trying to set the onclick property on a null value.

To solve the error, run the JS script after the DOM elements are available and make sure you only set the property on valid DOM elements.

ย