You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用appendChild报错Cannot read properties of 'null'该如何解决?

报错原因

你出现该报错的核心原因是原生HTML不存在className属性,该属性是React框架的专属写法,你在<ul>标签上错误使用className声明类名,导致浏览器无法识别该元素的类为notes:

错误代码片段:<ul className="notes" id="notes"></ul>
当JS执行document.querySelector(".notes")时,无法匹配到对应类名的元素,返回值为null,你对null调用appendChild方法就触发了当前报错。

修复方案

任选以下一种方案修改即可:

  • 方案一:修改HTML属性为原生标准写法
    将<ul>标签的className替换为HTML原生的class属性:
    <ul class="notes" id="notes"></ul>
    
  • 方案二:修改JS的元素选择逻辑
    不需要修改HTML,直接通过id选择器匹配元素即可:
    // 将原代码中的 let noteList = document.querySelector(".notes"); 替换为以下任意一行
    let noteList = document.querySelector("#notes");
    // 或者
    let noteList = document.getElementById("notes");
    

可选优化点

你代码中<input>标签的写法不规范,原生<input>是自闭合标签,不需要写</input>结束标签,修改为以下写法即可:

<input class="note-input" type="text" placeholder="Enter to-do item here">

内容的提问来源于stack exchange,提问作者Janine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 15:45:03