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

avatar

Borislav Hadzhiev

Last updated: Oct 19, 2021

banner

Check out my new book

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.

Use the search field on my Home Page to filter through my more than 3,000 articles.