Borislav Hadzhiev
Last updated: Oct 19, 2021
Check out my new book
The "Cannot set property 'href' of null" error occurs for 2 reasons:
href
property on a null
value (DOM element that doesn't
exist).Here's an example of how the error occurs.
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.
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.
<!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.
const link = document.getElementById('example'); console.log(link); // 👉️ a#example // ✅ Works link.href = 'https://google.com';
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.