I was doing to-do and I Got an error saying that :
const btn = document.querySelector('.functions button');
const list = document.querySelector('list');
const input = document.querySelector('.functions input');
btn.onclick = function(){
if(input.value.length == 0){
alert("Kindly Enter Task Name!!!!")
}
else{
list.innerHTML += `
<div class="task">
<span id="taskname">
${input.value}
</span>
</div>
`;
input.value = '';
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>To-Do List</title>
</head>
<body>
<div class="container">
<div class="list">
</div>
<div class="functions">
<input type="text">
<button>Add</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
The Error is
Uncaught TypeError: Cannot read properties of null (reading 'innerHTML')
3
Answers
The error you’re encountering, "
Uncaught TypeError: Cannot read properties of null (reading 'innerHTML')
," is because your list variable isnull
, meaning it couldn’t find an element with the class name ‘list
‘ when you tried to select it usingdocument.querySelector('list')
.Here’s the corrected JavaScript code:
Let’s trace back the error to make sense of it. If it says
Cannot read properties of null (reading 'innerHTML')
The only place you callinnerHTML
is here:list.innerHTML
So that means the
list
variable isnull
. You can double check this by addingconsole.log(list)
and see what the output is.So, why is that? Let’s take a look at where it is declared
That says it’s looking for a
<list>
HTML element… that’s not right! You are simply missing the.
before it to make it a valid CSS selector for an element<div class="list">
Now it works:
In the line
const list = document.querySelector('list');
you are trying to find an element of the form<list/>
, which, of course, does not exist in HTML at the moment and you getnull
.Correct the following line:
const list = document.querySelector('list');
on:
const list = document.querySelector('.list');
Result: