JavaScript 错误 : Uncaught TypeError: Cannot read property 'remove' of undefined

标签 javascript dom

我有一个脚本可以在添加成功后删除上传的文件,但是当它加载时我在网站上遇到了这个错误。

"Uncaught TypeError: Cannot read property 'remove' of undefined"

缺少什么?

<script>
onload=function() {
    document.querySelectorAll("li[id^='uploadNameSpan']")[0].remove();
}
</script>

最佳答案

基本上,您的问题是,在调用此代码时,DOM 中没有任何元素对应于查询 "li[id^='uploadNameSpan']" .所以 querySelectorAll 返回一个空的 NodeList0 位置(或与此相关的任何位置)有 undefined

发生的事情的分解:

var liElements = document.querySelectorAll("li[id^='uploadNameSpan']"); // this returns an empty NodeList

var nonExistentFirstElement = liElements[0]; // this is undefined, there's nothing at the first position

nonExistentFirstElement.remove(); // thus, this is an error since you're calling `undefined.remove()`

根据您的用例,您可以做的一件事是在尝试删除之前检查返回的项目数量:

var liElements = document.querySelectorAll("li[id^='uploadNameSpan']");
if (liElements.length > 0) {
  liElements[0].remove();
}

通常,您必须确保在尝试删除元素时该元素在 DOM 中。

关于JavaScript 错误 : Uncaught TypeError: Cannot read property 'remove' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38042716/

相关文章:

javascript - 将修改后的数组作为参数传递给函数

javascript - 如何通过 jQuery UI 使整个 DOM 可拖动和可调整大小?

javascript - 所有模块和 Controller 共享 Angular 范围

javascript - 无法将 "mysql2/promise"导入 Node.js 13/14 上的 ES 模块(MJS)

javascript - 多个字段的错误消息验证问题

javascript - 是否可以缓存/存档整个 Web 文档(包括 DOM 的精确状态)并稍后重新加载?

javascript - 提交登录表单而不单击登录按钮

javascript - HTML DOM 节点丢失事件

javascript - 动态添加的对象不会在 javascript 中获取样式

javascript - ReactJs setState 更改数组内对象的属性