Solve - Cannot read property 'click' of Null in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Check out my new book

Solve - Cannot read property 'click' of Null #

The "Cannot read property 'click' of null" error occurs for 2 reasons:

  1. Calling the click() method on a null value, e.g. a DOM element that doesn't exist.
  2. Placing the JS script tag above the HTML where the DOM elements are declared.

cannot read property click of null

Here is an example of how the error occurs.

index.js
const el = null; // ⛔️ Cannot read properties of null (reading 'click') el.click();

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

index.js
const el = document.getElementById('does-not-exist'); console.log(el); // 👉️ null // ⛔️ Cannot read properties of null (reading 'click') el.click();

We passed a non-existent id to the getElementById method and got a null value back.

Calling the click() method on a null value causes the error.

To solve the "Cannot read property 'click' 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.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ⛔️ BAD - script runs before button exists ⛔️ --> <script src="index.js"></script> <button id="btn" onclick="console.log('Button clicked')"> Do stuff </button> </body> </html>

Notice that the JS script tag is placed above the code that declares the button element. This means that the index.js file is ran before the button element is available.

index.js
const el = document.getElementById('btn'); console.log(el); // 👉️ null // ⛔️ Cannot read properties of null (reading 'click') el.click();

Instead, place the JS script tag at the bottom of the body, after all the DOM elements it tries to access.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <button id="btn" onclick="console.log('Button clicked')"> Do stuff </button> <!-- ✅ GOOD - button already exists ✅ --> <script src="index.js"></script> </body> </html>

Now we can access the button element inside of the index.js file.

index.js
const el = document.getElementById('btn'); console.log(el); // 👉️ button#btn // ✅ works el.click();

Conclusion #

The "Cannot read property 'click' of null" error occurs when trying to call the click method on a null value.

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

Use the search field on my Home Page to filter through my more than 3,000 articles.