window.onload执行时报Cannot read properties of null (reading 'children')错误如何解决
错误根因
你收到的Uncaught TypeError: Cannot read properties of null (reading 'children')报错,是因为document.getElementById没有匹配到对应ID的DOM元素,返回了null,后续读取null的children属性触发了类型错误。
你已经通过window.onload排除了DOM未加载的问题,问题出在DOM查询的参数写法上:
你调用了全局toString(currentCodeN)做类型转换,这个方法等价于Object.prototype.toString(),传入字符串参数时返回值为"[object String]",而非你预期的ID原值,自然查询不到对应元素。
修复方案
直接将currentCodeN作为参数传入getElementById即可,它本身就是字符串类型,不需要额外转换:
window.onload = function(){ console.log("h") for (i in bookData ){ var current = bookData[i] var currentCodeN = current.codeName // 移除多余的toString调用 var currentHTMLElem = document.getElementById(currentCodeN) // 可选:增加非空判断,避免偶发异常 if (!currentHTMLElem) { console.warn(`未查询到ID为${currentCodeN}的DOM节点`) continue } console.log(typeof(currentHTMLElem)) console.log(typeof(currentHTMLElem.children)); console.log(currentHTMLElem.children.length); } }
如果确实需要做类型转换,正确写法是调用变量自身的toString方法:currentCodeN.toString(),而非将变量作为参数传给全局toString方法。
内容的提问来源于stack exchange,提问作者Konny
相关产品推荐
相关产品推荐

