Solve - Cannot read property 'click' of Undefined in JS

avatar

Borislav Hadzhiev

Thu Oct 21 20212 min read

banner

Photo by Chad Madden

Solve - Cannot read property 'click' of Undefined #

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

  1. Calling the click() method on an undefined value (DOM element that doesn't exist).
  2. Placing the JS script tag above the HTML where the DOM elements are declared.
index.js
const el = undefined; // โŒ Cannot read properties of undefined (reading 'click') el.click();

To solve the "Cannot read property 'click' of undefined" error, make sure you're calling the click() method on a valid DOM element. The error often occurs when passing a non-existent class name to the getElementsByClassName method.

index.js
const el = document.getElementsByClassName('does-not-exist'); console.log(el); // ๐Ÿ‘‰๏ธ [] // โŒ Cannot read properties of undefined (reading 'click') el[0].click();

We passed a non-existent class name to the getElementsByClassName() method and got back an empty array-like object.

Trying to access an array at index that doesn't exist, returns an undefined value. Calling the click() method on an undefined value causes the error.

To solve the "Cannot read property 'click' of undefined" 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 class="btn" onclick="console.log('Button clicked')"> Click me </button> </body> </html>

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

index.js
const el = document.getElementsByClassName('btn'); console.log(el); // ๐Ÿ‘‰๏ธ [] // โŒ Cannot read properties of undefined (reading 'click') el[0].click();

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

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <button class="btn" onclick="console.log('Button clicked')"> Click me </button> <!-- โœ… GOOD - button already exists โœ… --> <script src="index.js"></script> </body> </html>

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

index.js
const el = document.getElementsByClassName('btn'); console.log(el); // ๐Ÿ‘‰๏ธ [button.btn] // โœ… Works ๐Ÿ‘๏ธ el[0].click();

Conclusion #

The "Cannot read property 'click' of undefined" error occurs when trying to call the click() method on an undefined 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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee