JS修改display属性报错cannot set properties of undefined如何解决?
报错原因
- 你调用
todoList.childNodes获取到的节点集合不止包含你创建的todo元素节点,还会包含DOM结构里的空白文本节点、注释节点等非元素节点,这类节点不存在style属性,当代码尝试访问todo.style.display时,todo.style本身是undefined,就会抛出这个类型错误。
修复方案
方案1:替换childNodes为children
children属性只会返回元素类型的子节点,自动过滤掉非元素节点,调整代码如下即可:
function filterTodo(e) { // 把childNodes换成children,children返回的是HTMLCollection,转成数组再调用forEach const todos = Array.from(todoList.children); todos.forEach(function(todo) { switch (e.target.value) { case "all": todo.style.display = "flex"; break; case "completed": if (todo.classList.contains("completed")) { todo.style.display = "flex"; } else { todo.style.display = "none"; } break; case "uncompleted": if (!todo.classList.contains("completed")) { todo.style.display = "flex"; } else { todo.style.display = "none"; } } }); }
方案2:遍历childNodes时加节点类型判断
如果一定要用childNodes,可以在遍历入口增加节点类型校验,非元素节点直接跳过:
todos.forEach(function(todo) { // nodeType为1代表是元素节点,其余类型直接跳过 if (todo.nodeType !== 1) return // 原有switch逻辑保持不变 })
内容的提问来源于stack exchange,提问作者ConnorS1702
相关产品推荐
相关产品推荐

