简体   繁体   English

嵌套div和'不能设置属性'innerHTML'为''错误

[英]Nested div and 'cannot set property 'innerHTML' of null' error

This error is typically due to the element being referenced before the DOM has fully loaded. 此错误通常是由于在DOM完全加载之前引用了元素。 As such, I've made sure to only run the required script once the window has loaded. 因此,我确保只在窗口加载后才运行所需的脚本。

Interestingly, if the getElementById() call is to a standalone <div> , ie a non-nested <div> , the innerHTML executes as desired. 有趣的是,如果getElementById()调用是一个独立的<div> ,即一个非嵌套的<div> ,则innerHTML会根据需要执行。 This therefore demonstrates that all the required naming conventions etc. are correct. 因此,这表明所有必需的命名约定等都是正确的。

The code: 编码:

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">

    (function(window, document, undefined) {
        window.onload = function() {
            google.charts.load('current', {
            packages:['corechart'],
            callback: drawChart
        });

        function drawChart() {

            var div1 = document.getElementById('div1');
            div1.innerHTML = 'DIV1';

            var div1_header = document.getElementById('div1_header');
            div1_header.innerHTML = "DIV1 HEADER";
        }
        };
    })(window, window.document);

</script>

</head>
<body>
    <div class="div" id="div1">
        <div class="div_header" id="div1_header"></div>
    </div>
<body>

As stated above, if I modify the code to the below, it works as expected: 如上所述,如果我修改下面的代码,它按预期工作:

<div class="div" id="div1"></div>
<div class="div_header" id="div1_header"></div>

How can the fact that the div1_header is nested be resulting in a 'null' error? div1_header嵌套的事实怎么会导致'null'错误?

The following line is replacing the innerHTML of div1 with 'DIV1'. 以下行将div1的innerHTML替换为'DIV1'。

div1.innerHTML = 'DIV1';

As a result div1_header no longer exists when you attempt to set its innerHTML. 因此,当您尝试设置其innerHTML时,div1_header不再存在。

By setting div1.innerHTML = 'DIV1'; 通过设置div1.innerHTML = 'DIV1'; you are deleting entire innerHTML of div1 (including div1_header) and replacing it with DIV1 text , so change that line into: 您正在deleting div1 (including div1_header)整个innerHTML div1 (including div1_header)并将其替换为DIV1 text ,因此将该行更改为:

var div1 = document.getElementById('div1');
div1.innerHTML += 'DIV1';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM