简体   繁体   English

TypeError:document.body为null

[英]TypeError: document.body is null

Why I getting error in browser? 为什么我在浏览器中出错?

TypeError: document.body is null TypeError:document.body为null

Code is working well in JSfiddle . 代码在JSfiddle中运行良好。

HTML HTML

<head>
    <meta charset="UTF-8">
    <title></title>
    <script src="jsscript.js"></script>
</head>
<body>
</body>

JS JS

var creElem = document.createElement("p");
creElem.innerHTML = "Hellow World";
creElem.setAttribute("id", "id_name");
document.body.appendChild(creElem);

Execute the code when the DOM loads. 在DOM加载时执行代码。 Wrap your logic in an event listener for DOMContentLoaded . 将您的逻辑包装在DOMContentLoaded的事件侦听器中。

document.addEventListener('DOMContentLoaded', function () {
    // ...
});

The reason it worked in JSFiddle is because the JS is executed on load (that's the default option in JSFiddle). 它在JSFiddle中工作的原因是因为JS是在加载时执行的(这是JSFiddle中的默认选项)。


Alternatively, depending on when you need the logic to be executed, you could also use: 或者,根据您何时需要执行逻辑,您还可以使用:

window.addEventListener('load', function () {
    // ...
});

See: Difference between DOMContentLoaded and Load events 请参阅: DOMContentLoaded和Load事件之间的区别

Your document.body is not crated or existed yet. 您的document.body尚未创作或存在。 If you want to append child to document.body or do anything with document.body in your javascript then put your javascript cod or link of js file in the end of body tag. 如果你想将child附加到document.body或在你的javascript中使用document.body做任何事情,那么将你的javascript cod或js文件的链接放在body标签的末尾。

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        <script src="jsscript.js"></script>
    </body>
</html>

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

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