未捕获的类型错误:document.getElementById(..)为null



我正在学习JavaScript并制作简单列表网站。当我想通过错误将我的数据保存到本地主机时

我的JavaScript代码将数据保存到本地存储


<script>
add = document.getElementById("add");
add.addEventListener("click", () => 
{
console.log("Updating...");
let tit = document.getElementById("title").value;
let desc = document.getElementById("description").value;
if (localStorage.getItem('itemsJson') == null) {
itemJsonArray = [];
itemJsonArray.push([tit, desc]);
localStorage.setItem('itemsJson', JSON.stringify(itemJsonArray));
}
if (localStorage.getItem('itemsJson') != null) 
{
console.log("Added Successfully!");
}
});
</script>

每次都会出现错误

Uncaught TypeError: document.getElementById(...) is null
<anonymous>      http://127.0.0.1:5500/ToDoList/ToDoList.html:112
EventListener.handleEvent*   http://127.0.0.1:5500/ToDoList/ToDoList.html:110ToDoList.html:112:32
<anonymous> http://127.0.0.1:5500/ToDoList/ToDoList.html:112
(Async: EventListener.handleEvent)
<anonymous> http://127.0.0.1:5500/ToDoList/ToDoList.html:110```

您没有为正在操作的元素添加足够的属性。请检查此链接我的解决方案。我已经解决了你的问题。或者你可以使用这个片段。<input type="text" id="title"><textarea type="text" id="description"></textarea><button id="add">ADD</button>