Js 中 Cannot read property 'appendChild' of Undefined 错误
“Cannot read property 'appendChild' of Undefined”错误的发生有两个原因:
-
在不存在的 DOM 元素上调用
appendChild
方法。 - 在声明 DOM 元素的 HTML 上方插入 JS 脚本标记。
下面是一个产生上述错误的示例代码
const el = undefined;
const p = document.createElement('p');
// ⛔️ Uncaught TypeError: Cannot read properties of undefined (reading 'appendChild')
el.appendChild(p);
该错误最常发生在访问不存在的索引处的数组之后,例如 在调用 getElementsByClassName
之后。
const arr = [];
const p = document.createElement('p');
// ⛔️ Cannot read properties of undefined (reading 'appendChild')
arr[0].appendChild(p);
要解决“Cannot read property 'appendChild' of null”错误,请确保调用 appendChild()
方法的 DOM 元素包含在 DOM 中。
const elements = document.getElementsByClassName('does-not-exist');
console.log(elements); // 👉️ []
const p = document.createElement('p');
// ⛔️ Cannot read properties of undefined (reading 'appendChild')
elements[0].appendChild(p);
因为我们为 getElementsByClassName
方法提供了一个无效的类名,它返回一个空的类数组对象,所以访问它的第 0 个索引返回未定义,导致错误。
要解决“Cannot read property 'appendChild' of null”错误,在声明所有 DOM 元素后,在 body 标签底部插入 JS script
标签。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<!-- ⛔️ BAD - script is run before div exists ⛔️ -->
<script src="index.js"></script>
<div class="box"></div>
</body>
</html>
因为我们将 JS 脚本标记放在 div 元素之上,所以在将 div 元素添加到 DOM 之前运行 index.js 文件。
如果我们现在运行 index.js 文件, div 元素将不可用。
const boxes = document.getElementsByClassName('box');
console.log(boxes); // 👉️ []
const p = document.createElement('p');
// ⛔️ Cannot read properties of undefined (reading 'appendChild')
boxes[0].appendChild(p);
在声明 HTML 之后,我们必须将 JS 脚本标记放在正文的底部。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
</head>
<body>
<div class="box"></div>
<!-- ✅ GOOD - div already exists ✅ -->
<script src="index.js"></script>
</body>
</html>
现在我们可以访问 index.js 文件中的 div 元素。
const boxes = document.getElementsByClassName('box');
console.log(boxes); // 👉️ [div.box]
const p = document.createElement('p');
// ✅ works
boxes[0].appendChild(p);
总结
当我们尝试对未定义的值调用 appendChild()
方法时,会抛出“Cannot read property 'appendChild' of Undefined”错误。
要解决该错误,需要确保仅对有效的 HTML 元素调用该方法。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
将 Pandas DataFrame 转换为 JSON
发布时间:2024/04/21 浏览次数:153 分类:Python
-
本教程演示了如何将 Pandas DataFrame 转换为 JSON 字符串。
在 Pandas 中加载 JSON 文件
发布时间:2024/04/21 浏览次数:105 分类:Python
-
本教程介绍了我们如何使用 pandas.read_json()方法将一个 JSON 文件加载到 Pandas DataFrame 中。
将 JSON 转换为 Pandas DataFrame
发布时间:2024/04/20 浏览次数:135 分类:Python
-
本教程演示了如何使用 json_normalize()和 read_json()将 JSON 字符串转换为 Pandas DataFrame。
从 JavaScript 中的 JSON 对象获取值
发布时间:2024/03/22 浏览次数:177 分类:JavaScript
-
通过 JSON.parse() 方法访问 JavaScript 中的 JSON 对象和数组可以有多种做法。可以使用点(.) 操作或括号对([]) 访问它。