How to Fix "cannot set properties of null" Errors in JS
The "Uncaught TypeError: Cannot set properties of null (setting 'value')" error occurs in JavaScript, whenever you try to set a property on an object that is null
. In order to fix the error, you need to ensure that the object exists, and its value is not null
.
// β This will throw Uncaught TypeError: Cannot set properties of null (setting 'value')
const input = null
input.value = 'new value'
The error also specifies that you tried to set the value
property on the object. This usually happens when you work with input DOM elements, and you want to set their value, but the DOM element doesn't exist.
If this is the case, you want to check whether you query the right element, or if the element exists at all. You can do this in the following way:
// Check whether your query returns null
const input = document.querySelector('input')
// β This can also throw an error
input.value = 'new value'
// βοΈ This will only set the value if the input exists
if (input) {
input.value = 'new value'
}
The error can also happen if you try to query the element before the DOM is created. To resolve this, check whether your script comes before you define the DOM element, and change the order. Move your script before the closing of your body
tag.
<!-- β This will not work as the DOM element doesn't exist at this point -->
<script>
const input = document.querySelector('input')
input.value = 'new value'
</script>
<input />
<!-- βοΈ This will work as the input is already created by the time the script is executed -->
<input />
<script>
const input = document.querySelector('input')
input.value = 'new value'
</script>
</body>
This happens because your HTML file is read from top to bottom. When your browser comes across a script
tag, it will try to execute the JavaScript inside it, but the DOM elements are only coming after the script.
This means it will not find the element, and in order to solve this issue, you need to switch around the order to make sure your DOM elements are already created by the time you want to interact with it through JavaScript.
You can also use async or defer to ensure your DOM is loaded before executing JavaScript.
If you are not working with DOM elements, but with simple JavaScript objects, you can also use a logical OR to ensure that you are working with object.
const selector = null
const input = selector || {}
// βοΈ This will work, as even if `selector` is null, we will assign an empty object
input.value = 'new value'
This works as a fallback. Whenever selector
is null
, it will fall back to using an empty object, meaning we will ensure that input
will always be an object.
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: