Solve - Cannot set property 'href' of Null in JavaScript

avatar

Borislav Hadzhiev

Tue Oct 19 20212 min read

banner

Photo by Tim Gouw

Solve - Cannot read property 'href' of Null #

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

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

cannot set property href of null

Here's an example of how the error occurs.

index.js
const link = null; // โ›”๏ธ Cannot set properties of null (setting 'href') link.href = 'https://google.com';

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

index.js
const link = document.getElementById('does-not-exist'); console.log(link); // ๐Ÿ‘‰๏ธ null // โ›”๏ธ Cannot set properties of null (setting 'href') link.href = 'https://google.com';

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

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

To solve the "Cannot set property 'href' 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> <a id="example" href="https://example.com">Example</a> <!-- โœ… GOOD - link already exists โœ… --> <script src="index.js"></script> </body> </html>

The link element is created before the index.js script is ran, therefore the script has access to it.

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

index.js
const link = document.getElementById('example'); console.log(link); // ๐Ÿ‘‰๏ธ a#example // โœ… Works link.href = 'https://google.com';

Conclusion #

The "Cannot set property 'href' of null" error occurs when trying to set the href 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 valid DOM 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