Last updated: Mar 3, 2024
Reading timeยท2 min

The "Cannot read properties of null (reading 'parentNode')" error occurs for 2 reasons:
parentNode property on a null value (a DOM element that
doesn't exist).
Here is an example of how the error occurs.
const content = document.getElementById('does-not-exist'); console.log(content); // ๐๏ธ null // โ๏ธ Uncaught TypeError: Cannot read properties of null (reading 'parentNode') const parentNode = content.parentNode;
We attempted to access the parentNode property on a null value which caused
the error.
parentNodeTo solve the error, make sure to use the correct id when getting the DOM
element.
The error often occurs when passing an invalid id to the getElementById
method.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div> <!-- ๐๏ธ `id` should match your JS code --> <div id="content">Content</div> </div> <script src="index.js"></script> </body> </html>
The id of the element in your HTML code should match the id you specified in
the call to the document.getElementById() method in your JavaScript code.
Place the JS script tag at the bottom of the body.
The JS script tag should run after the DOM elements have been declared.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- โ๏ธ BAD - script is run before div is created โ๏ธ --> <script src="index.js"></script> <div> <div id="content">Content</div> </div> </body> </html>
index.js file is run before the two div elements are created, so you can't access the elements inside of the index.js file.const content = document.getElementById('content'); console.log(content); // ๐๏ธ null // โ๏ธ Cannot read properties of null (reading 'parentNode') const parentNode = content.parentNode;
You should place the index.js script tag at the bottom of the body tag, after
all the DOM elements have been declared.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div> <div id="content">Content</div> </div> <!-- โ GOOD - divs are already created โ --> <script src="index.js"></script> </body> </html>

Now the div elements will be accessible inside of the index.js file.
const content = document.getElementById('content'); console.log(content); // ๐๏ธ div#content // โ Works const parentNode = content.parentNode; console.log(parentNode); // ๐๏ธ div

HTML code is parsed from top to bottom, so the script tag has to be placed at the bottom of the body tag, after all of the DOM elements it needs to access.
Things to note when using the parentNode property:
parentNode property on a Document or
DocumentFragment nodes returns null - they can never have a parent.null if the HTML element has been created but not yet
attached to the DOM.To solve the "Cannot read properties of null (reading 'parentNode')" error,
make sure to use the correct id when getting the DOM element.
The error often occurs when passing an invalid id to the getElementById
method.