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

React中Uncaught TypeError: Cannot read properties of undefined (reading 'add')错误解决

解决"Cannot read properties of undefined (reading 'add')"错误

错误原因

  • document.getElementsByClassName() 返回的是HTMLCollection(元素集合),不是单个DOM元素,直接访问集合的classList会返回undefined,调用add()时自然报错。
  • 属性名拼写错误:正确的DOM元素属性是classList,不是classNameList。

修正方案

根据你的HTML结构(仅存在一个带not-found-animation类的元素),有两种可行的修正方式:

方式1:使用querySelector获取单个元素(推荐)

querySelector可直接匹配第一个符合选择器的元素,更适配单个元素的场景:

setTimeout(function () {
  const notFoundElement = document.querySelector(".not-found-animation");
  notFoundElement.classList.add("hinge-falling");

  console.log("setTimeout Loaded...");
}, 2200);

方式2:从元素集合中取第一个元素

如果坚持使用getElementsByClassName,需要从返回的集合中取出目标元素,同时增加判断避免元素不存在时再次报错:

setTimeout(function () {
  const notFoundElements = document.getElementsByClassName("not-found-animation");
  if (notFoundElements.length > 0) {
    notFoundElements[0].classList.add("hinge-falling");
    console.log("setTimeout Loaded...");
  }
}, 2200);

额外注意

如果是原生HTML文件,要把HTML代码里的className改成class(className是React等框架的语法,原生HTML使用class):

<h1 class="not-found-animation">404</h1>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 12:27:05