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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 04:27:02