Last updated: Mar 7, 2024
Reading timeยท2 min
The "Cannot read properties of null (reading 'focus')" error occurs for 2 reasons:
focus()
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 'focus') el.focus();
Make sure the id
you're using to get the element exists in the DOM.
The error often occurs after providing an invalid id
to the getElementById
method.
const el = document.getElementById('does-not-exist'); console.log(el); // ๐๏ธ null // โ๏ธ Uncaught TypeError: Cannot read properties of null (reading 'focus') el.focus();
We passed an id
that doesn't exist to the getElementById
method and got a
null
value back.
Calling the focus() 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 is run before input exists โ๏ธ --> <script src="index.js"></script> <input type="text" id="first_name" value="John" /> </body> </html>
The JS script tag is placed above the input
element, so the index.js
file is
run before the input
element is present in the DOM.
const el = document.getElementById('first_name'); console.log(el); // ๐๏ธ null // โ๏ธ Cannot read properties of null (reading 'focus') el.focus();
The JS script tag should be placed at the bottom of the body
tag, after the
elements the file needs access to.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <input type="text" id="first_name" value="John" /> <!-- โ GOOD - input already exists โ --> <script src="index.js"></script> </body> </html>
Now we have access to the input
element in the index.js
file.
const el = document.getElementById('first_name'); console.log(el); // ๐๏ธ input#first_name // โ Works el.focus();
HTML code is parsed from top to bottom, so the script
tag has to come after
the code that declared the DOM elements.
Otherwise, the elements aren't accessible in the index.js
file.
The "Cannot read properties of null (reading 'focus')" error occurs when trying
to call the focus()
method on a null
value.
To solve the error, run the JS script after the DOM elements are available and make sure you only call the method on valid DOM elements.