Solve - Cannot set property 'checked' of Null in JS

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Jeremy Bishop

Solve - Cannot set property 'checked' of Null #

The "Cannot set property 'checked' of null" error occurs for 2 reasons:

  1. Setting the checked property on a null value (input element that doesn't exist).
  2. Placing the JS script tag above the HTML where the DOM elements are declared.

cannot set property checked of null

Here's an example of how the error occurs.

index.js
const input = null; // โ›”๏ธ Cannot set properties of null (setting 'checked') input.checked = true;

To solve the "Cannot set property 'checked' of null" error, make sure the id you're using to get the element is present in the DOM. The error often occurs after providing a non-existent id to the getElementById method.

index.js
const input = document.getElementById('does-not-exist'); console.log(input); // ๐Ÿ‘‰๏ธ null // โ›”๏ธ Cannot set properties of null (setting 'checked') input.checked = true;

We passed a non-existent id to the getElementById method and got a null value back.

Setting the checked property on a null value causes the error.

To solve the "Cannot set property 'checked' of null" error, place the JS script tag at the bottom of the body tag. The script should run after the DOM elements have been created.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <!-- โ›”๏ธ BAD - script is ran before input is created โ›”๏ธ --> <script src="index.js"></script> <input type="checkbox" name="subscribe" id="subscribe" /> </body> </html>

We placed the JS script tag above the code that creates the input element. This means that the index.js file is ran before the input is created, therefore we don't have access to the input element in the index.js file.

index.js
const input = document.getElementById('subscribe'); console.log(input); // ๐Ÿ‘‰๏ธ null // โ›”๏ธ Cannot set properties of null (setting 'checked') input.checked = true;

The JS script tag should be moved to the bottom of the body, after all of the DOM elements it needs access to.

index.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <input type="checkbox" name="subscribe" id="subscribe" /> <!-- โœ… GOOD - input already exists โœ… --> <script src="index.js"></script> </body> </html>

Now, the index.js file has access to the input element.

index.js
const input = document.getElementById('subscribe'); console.log(input); // ๐Ÿ‘‰๏ธ input#subscribe // โœ… Works input.checked = true;

Conclusion #

The "Cannot set property 'checked' of null" error occurs when trying to set the checked property on a null value.

To solve the error, run the JS script after the DOM elements are available and make sure you only set the property on existing input elements.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee