Borislav Hadzhiev
Sat Oct 23 2021·2 min read
Photo by Munbaik Cycling
The "Cannot read property 'remove' of undefined" error occurs for 2 reasons:
remove()
method on a DOM element that doesn't exist.Here is an example of how the error occurs.
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.
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.
<!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 ran before the div elements are created.
This means that the div elements will not be accessible in the index.js
file.
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.
<!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.
const boxes = document.getElementsByClassName('box'); console.log(boxes); // 👉️ [div.box, div.box] // ✅ Works boxes[0].remove();
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.