Borislav Hadzhiev
Sat Oct 23 2021·2 min read
Photo by Florencia Viadana
The "Cannot read property 'appendChild' of null" error occurs for 2 reasons:
appendChild()
method on a DOM element that doesn't exist, e.g
calling getElementById
with invalid id.Here is an example of how the error occurs.
const el = null; const p = document.createElement('p'); // ⛔️ Cannot read properties of null (reading 'appendChild') el.appendChild(p);
To solve the "Cannot read property 'appendChild' of null" error, make sure the
DOM element on which you're calling the method exists. The error often occurs
after providing an invalid id to the getElementById
method.
const el = document.getElementById('does-not-exist'); console.log(el); // 👉️ null const p = document.createElement('p'); // ⛔️ Cannot read properties of null (reading 'appendChild') el.appendChild(p);
Because we provided an id
that doesn't exist in the DOM, we got back a null
value, on which we tried to call the appendChild
method and got the error.
To solve the "Cannot read property 'appendChild' of null" error, make sure to insert the JS script tag at the bottom of the body. The JS script tag should be placed after the HTML elements have been declared.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- ⛔️ BAD - script is ran before HTML is declared ⛔️ --> <script src="index.js"></script> <div id="box"></div> </body> </html>
Because we placed the JS script tag above the div
element, the index.js
file
is ran before the DOM element is created.
This means that we are unable to access the div
in the index.js
file.
const el = document.getElementById('box'); console.log(el); // 👉️ null const p = document.createElement('p'); // ⛔️ Cannot read properties of null (reading 'appendChild') el.appendChild(p);
You have to place the JS script tag at the bottom of the body, after the DOM elements have been declared.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box"></div> <!-- ✅ GOOD - HTML is already available ✅ --> <script src="index.js"></script> </body> </html>
Now you can access the div
element inside of the index.js
file.
const el = document.getElementById('box'); console.log(el); // 👉️ div const p = document.createElement('p'); // ✅ works el.appendChild(p);
The "Cannot read property 'appendChild' of null" error occurs when trying to
call the appendChild
method on a DOM element that doesn't exist.
To solve the error, make sure to only call the appendChild
method on valid DOM
elements.