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

avatar

Borislav Hadzhiev

Sat Oct 23 20212 min read

Solve - Cannot read property 'remove' of Undefined #

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

  1. Calling the remove() method on a 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 'remove') el.remove();

To solve the "Cannot read property 'remove' of undefined" error, make sure to provide a valid identifier when getting the DOM elements. The error often occurs when passing an invalid class name to the getElementsByClassName method.

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

Because the class name is not found in the DOM, the getElementsByClassName() method returns an empty array-like object.

Trying to access an array at an index that doesn't exist returns undefined, causing the error.

To solve the "Cannot read property 'remove' of undefined" error, make sure the JS script tag is placed 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 divs are created โ›”๏ธ --> <script src="index.js"></script> <div class="box">Box 1</div> <div class="box">Box 2</div> </body> </html>

Notice that the index.js script is executed before the div elements are created. This means that the div elements will not be accessible in the index.js file.

index.js
const boxes = document.getElementsByClassName('box'); console.log(boxes); // ๐Ÿ‘‰๏ธ [] // โ›”๏ธ Cannot read properties of undefined (reading 'remove') boxes[0].remove();

Instead, you should place the JS script tag at the bottom of the body, after the div elements are declared.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div class="box">Box 1</div> <div class="box">Box 2</div> <!-- โœ… GOOD - div elements are already created โœ… --> <script src="index.js"></script> </body> </html>

Now the index.js file has access to the div elements.

index.js
const boxes = document.getElementsByClassName('box'); console.log(boxes); // ๐Ÿ‘‰๏ธ [div.box, div.box] // โœ… Works boxes[0].remove();

Conclusion #

The "Cannot read property 'remove' of undefined" error occurs when the remove() method is called on an undefined value.

To solve the error, make sure to only call the remove 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