Last updated: Mar 2, 2024
Reading timeยท2 min
The "TypeError: Cannot read properties of null (reading 'getAttribute')" occurs for 2 reasons:
getAttribute()
method on a null
value (DOM element that
doesn't exist).Here is an example of how the error occurs.
const el = null; // โ๏ธ Uncaught TypeError: Cannot read properties of null (reading 'getAttribute') el.getAttribute('id');
Make sure the id
you're using to get the element exists in the DOM.
The error often occurs after providing a non-existent id
to the
getElementById
method.
const el = document.getElementById('does-not-exist'); console.log(el); // ๐๏ธ null // โ๏ธ Cannot read properties of null (reading 'getAttribute') const id = el.getAttribute('id');
We passed a non-existent id
to the getElementById()
method and got a null
value back.
Calling the getAttribute()
method on a null
value causes the error.
Place the JS script tag 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 button exists โ๏ธ --> <script src="index.js"></script> <div id="box">Test</div> </body> </html>
The JS script tag is placed above the code that declares the div
element, so
the div
element is not accessible from the index.js
file.
const el = document.getElementById('box'); console.log(el); // ๐๏ธ null // โ๏ธ Cannot read properties of null (reading 'getAttribute') const id = el.getAttribute('id');
Instead, move the JS script tag to the bottom of the body tag, after the DOM elements it needs access to.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">Test</div> <!-- โ GOOD - div already exists โ --> <script src="index.js"></script> </body> </html>
Now we can access the div
element inside of the index.js
file.
const el = document.getElementById('box'); console.log(el); // ๐๏ธ div#box // โ Works const id = el.getAttribute('id'); console.log(id); // ๐๏ธ box
getAttribute
method returns either null
or an empty string.To solve the "TypeError: Cannot read properties of null (reading
'getAttribute')" error, make sure the id
you're using to get the element
exists in the DOM.
The error often occurs after providing a non-existent id
to the
getElementById
method.