Currently having issues with this code for a while, and I keep getting errors no matter how much i check it out.
The errors are all the same:
TypeError: Cannot set property ‘textContent’ of null
when i’m using querySelector or when i’m using getElementById as well. I don’t know if it’s my HTML or if i’m imputing it wrong.
what i’m getting confused in is it works here… but the error pops up when i’m using my VSC (visual studio code) and running it on chrome, the error shows up. Is it my code or the VSC?
var dice = Math.floor(Math.random()* 6) +1;
document.querySelector("#current-0").textContent = dice;
<div class="wrapper clear-fix">
<div class="player1-panel active">
<div class="player-name" id="player-1">Player 1</div>
<div class="player-score" id="score-1">100</div>
<div class="player-current-box">
<div class="player-current-label">Current</div>
<div class="player-current-score" id="current-0">11</div>
</div>
</div>
<div class="player2-panel">
<div class="player-name" id="player-2">Player 2</div>
<div class="player-score" id="score-2">00</div>
<div class="player-current-box">
<div class="player-current-label">Current</div>
<div class="player-current-score" id="currentScore-2">00</div>
</div>
</div>
<button class="btn-rules"><i class="material-icons">
help</i>Rules</button>
<button class="btn-newGame"><i class="material-icons">
add_circle_outline
</i>New Game</button>
<button class="btn-rollDice"><i class="material-icons">
autorenew</i>Roll dice</button>
<button class="btn-hold"><i class="material-icons">
play_for_work</i>Hold</button>
<input type="text" placeholder="Goal" class="finalScore">
<img src="images/dice5.png" atl="dice" class="dice" id="dice1">
<img src="images/dice5.png" atl="dice" class="dice" id="dice2">
</div>
Vue version
3.2.47
Link to minimal reproduction
https://stackblitz.com/edit/vitejs-vite-pe69dq?file=src/App.vue
Steps to reproduce
- Open reproduction link with Chrome/Firefox
- Edit the text in the App.vue template
- HMR will crash with type error in console and changes are not visible in preview window
What is expected?
HMR should not crash when working with external components
What is actually happening?
Changes to template are not visible without a full reload, and I get the following error in browser console:
TypeError: Cannot set properties of null (setting 'textContent')
...
[HMR] Something went wrong during Vue component hot-reload. Full reload required.
System Info
Tested in Google Chrome and Firefox, on Ubuntu 22.10
Any additional comments?
I run into this bug a lot while working on applications that use components imported from npm component libraries.
This closed thread is also possibly related to this issue: #4707
если повторно ввести такое же значение то поиск не работает
<div class="findc">
<input type="text" id="text-to-find" placeholder="Введите название или код" value=""><input type="button" id="search-button" onclick="findString(document.getElementById('text-to-find').value)" value="Искать"/>
</div>
</div>
<div id="probel">
</div>
<div id="kod-name">
<div id="kod">
Код
</div>
<div id="name">
Наименование
</div>
</div>
<div id="fkko">
<div class="kod"> 17935111614 </div> <div class="name"> отходы сетей и сетепошивочного материала из полиамидного волокна </div>
<div class="kod"> 30111411204 </div> <div class="name"> шрот шиповника </div>
<div class="kod"> 30111512103 </div> <div class="name"> сливы ароматизаторов на масляной основе при производстве пищевых продуктов </div>
<div class="kod"> 30111513324 </div> <div class="name"> остатки заменителей сахара при производстве пищевых продуктов </div>
<div class="kod"> 30111514104 </div> <div class="name"> остатки сахарного сиропа при производстве пищевых продуктов </div>
<div class="kod"> 30111515204 </div> <div class="name"> остатки сухих и сыпучих подсластителей и ароматизаторов при производстве пищевых продуктов </div>
<div class="kod"> 30111531394 </div> <div class="name"> отходы хлорида натрия при приготовлении раствора поваренной соли в производстве пищевых продуктов </div>
<div class="kod"> 30111611314 </div> <div class="name"> остатки растительных масел при производстве пищевых продуктов </div>
<div class="kod"> 30111612294 </div> <div class="name"> нагар растительных масел при производстве пищевых продуктов </div>
<div class="kod"> 30111614304 </div> <div class="name"> масло пальмовое, отработанное при производстве пищевых продуктов </div>
<div class="kod"> 30111811724 </div> <div class="name"> отходы упаковки из разнородных материалов в смеси, загрязненные пищевым сырьем биологического происхождения </div>
function findString(text) {
document.querySelector("#output").textContent=window.find(text);
}
As a web developer, you’re bound to encounter errors when working with JavaScript. Coding errors stop the program from doing what is expected.
To be able to fix these errors, you need to be able to understand the error message, as this will help you comprehend why the error was raised and how to fix it.
In this tutorial, we’ll talk about the “uncaught typeerror: cannot set property” error in JavaScript.
You’ll learn why this error occurs, the different reasons why you might encounter it, and the different methods of fixing it.
What Does “Uncaught Typeerror: Cannot Set Property” Mean in JavaScript?
A typeerror mainly occurs when you perform an operation involving incompatible data types. In our case, we’re dealing with the “uncaught typeerror: cannot set property” error, a JavaScript error which mainly occurs when you try to assign a property to a DOM element with a null value.
This error can be raised for different reasons like:
- Placing the
scripttag in the wrong position in your markup - Spelling errors when referencing DOM elements
- Accessing an undefined or invalid DOM element
In the sections that follow, we’ll discuss the reasons above, how they can throw the “uncaught typeerror: cannot set property” error with code examples, and how to fix the error.
We’ll also talk about how you can determine if a variable is null or undefined.
Let’s get started!
How To Fix the “uncaught typeerror: cannot set property” in JavaScript
In this section, you’ll get to know the common causes of the “uncaught typeerror: cannot set property” error in JavaScript. Each subsection that follows is dedicated to one of those causes and its solution.
You’ll also get to visualize how to fix the error with some practical code examples.
Invalid Placement of script Tag
When a webpage loads, the JavaScript code written for the page loads as well. The way JavaScript recognizes the Document Object Model (DOM) is dependent on where you place the script tag in your code.
If you place the script tag within the head tag or above all the HTML elements within the body tag, then the script will be executed before the DOM is ready.
When JavaScript runs before the DOM is ready, it fails to get a full representation of the DOM — which means most of your variables linked to DOM elements will return as null.
Here’s an example of a code that would raise the “uncaught typeerror: cannot set property” error in JavaScript because of the position of the script tag:
<!DOCTYPE html>
<html>
<head>
<title>Uncaught Typeerror Error Tutorial</title>
<script src="app.js"></script>
</head>
<body>
<h1 id="heading"></h1>
</body>
</html>
The code above has the script tag placed within the head tag. We also have a h1 element with an id of heading.
Next, we’ll try to assign text to the h1 element:
let heading = document.getElementById('heading');
heading.textContent = 'This is a heading';
//Uncaught TypeError: Cannot set properties of null (setting 'textContent')
Although the code above looks fine, the “uncaught typeerror: cannot set property” error was raised. This happened because the script had already loaded before the DOM, so our JavaScript had no knowledge of the DOM elements.
This error will also be raised if you place the script tag above other DOM elements:
<!DOCTYPE html>
<html>
<head>
<title>Uncaught Typeerror Error Tutorial</title>
</head>
<body>
<script src="app.js"></script>
<h1 id="heading"></h1>
</body>
</html>
Now the script tag is above the DOM elements in the body tag, but it will still raise the “uncaught typeerror: cannot set property” error because the script loads before the DOM.
To fix this error, you have to put the script tag just before the closing body tag. This way, all the DOM elements will load before the script.
Here’s an example of correct placement:
<!DOCTYPE html>
<html>
<head>
<title>Uncaught Typeerror Error Tutorial</title>
</head>
<body>
<h1 id="heading"></h1>
<script src="app.js"></script>
</body>
</html>
let heading = document.getElementById('heading');
heading.textContent = 'This is a heading'
When the code above is executed, the h1 element will have its textContent set to “This is a heading”. There will be no error.
Spelling Errors
Spelling errors are another source of raising the “uncaught typeerror: cannot set property” error.
When you misspell the attribute (ID or class) used to identify a DOM element in JavaScript, you make reference to a nonexistent element, which will return a null value.
Trying to assign a value to a null value will raise the “uncaught typeerror: cannot set property” error.
Here’s a code example to help you understand:
<!DOCTYPE html>
<html>
<head>
<title>Uncaught Typeerror Error Tutorial</title>
</head>
<body>
<h1 id="heading"></h1>
<script src="app.js"></script>
</body>
</html>
let heading = document.getElementById('headin');
heading.textContent = 'Hello World!'
//Uncaught TypeError: Cannot set properties of null (setting 'textContent')
In the code above, we have a h1 tag with an id of heading.
In the JavaScript code, we made reference to the id but with a spelling error. Instead of “heading”, we wrote “headin” — that is, document.getElementById('headin'); instead of document.getElementById('heading');.
To avoid such errors, always make sure that your DOM elements are referenced properly, using the right attribute with matching spelling.
Accessing an Undefined DOM Element
In the last section, we saw how referencing a misspelled attribute can raise an “uncaught typeerror: cannot set property” error. The same is the case when we try to access a DOM element that doesn’t exist.
In the example below, we’ll try to access an id attribute that is yet to be defined in the markup:
<!DOCTYPE html>
<html>
<head>
<title>Uncaught Typeerror Error Tutorial</title>
</head>
<body>
<h1></h1>
<script src="app.js"></script>
</body>
</html>
let heading = document.getElementById('headin');
heading.textContent = 'Hello World!'
//Uncaught TypeError: Cannot set properties of null (setting 'textContent')
As can be seen above, we’re trying to set the textContent of a DOM element that doesn’t exist. There is no element in our HTML code that has an id of “heading”, so this returns a null value.
If you go on to log the heading variable to the console, you’ll get a value of null returned.
How To Determine if a Variable Is ‘null’ or ‘undefined’
By this point, you’ve understood that assigning a value to a variable that is null or undefined will most likely raise an “uncaught typeerror: cannot set property” error.
But you can determine if a variable is null or undefined; before interacting with them. Although this does not fix the error, it gives some clarity on why a functionality isn’t working.
Before we discuss how to determine if a variable is null or undefined in JavaScript, it’s important to understand the difference between a null and an undefined value.
A variable is null when an empty or unknown value is assigned to the variable. The previous sections of this tutorial show practical examples of a null variable.
On the other hand, a variable is undefined when no value has been assigned to it:
let age;
console.log(age);
// undefined
In the code above, the age variable was declared, but no value was assigned to it. When logged to the console, undefined was returned.
Now that you know the difference between null and undefined, let’s have a look at how you can determine if a variable is either of those.
You can use the loose equality operator (==) to determine if a variable is either null or undefined. Here’s an example:
<!DOCTYPE html>
<html>
<head>
<title>Uncaught Typeerror Error Tutorial</title>
</head>
<body>
<h1 id="headin"></h1>
<script src="app.js"></script>
</body>
</html>
let heading = document.getElementById('headin');
if (heading == null) {
console.log('Variable is null - cannot assign value to a null variable');
} else {
heading.textContent = 'Hello World!';
}
In the code above, we made a spelling error when referencing a DOM element in JavaScript.
Using an if statement, we checked to see if the value of the heading variable was null: if (heading == null) {...}
Since it returned a null value, “Variable is null – cannot assign value to a null variable” would be logged out in the console. If we had not gotten a null value, then the code in the else block would have been executed.
If you’re wondering why we didn’t include undefined in the if statement, this is because null == undefined in JavaScript, so the code in the if statement checks for both errors.
Summary
Error messages can be confusing in some cases, but they help developers figure out why their code isn’t working in order to fix it and avoid future occurrences.
Although nobody loves errors, they’re a good way to help you understand your favorite programming language better.
Struggling with this pesky error in your JavaScript code? Fix it and avoid common pitfalls like accessing undefined or invalid DOM elements — all in this guide 🤓Click to Tweet
What’s more, fixing a coding error gives you more context when you encounter a similar error in a different project. The error we’ve discussed in this article isn’t only raised when working on vanilla JavaScript projects — you can also encounter it when working with JavaScript frameworks and libraries.
If you’re going to build an app or website, there’s a variety of skills to learn and a lot of practice required to use these skills efficiently. Kinsta’s new Hobby Tier provides the perfect hosting platform for everyone who needs a space to practice, from burgeoning new coders to experienced developers looking to advertise their work or deploy proof-of-concept apps. And if you sign up for any tier today, you’ll get $20 off your first month.
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'
Copied to clipboard!
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'
}
Copied to clipboard!
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>
Copied to clipboard!
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'
Using logical OR to ensure the object is not null
Copied to clipboard!
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.
