javascript 类型错误:document.body 为空

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27833117/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 08:03:38  来源:igfitidea点击:

TypeError: document.body is null

javascripttypeerror

提问by Getup4

Why I getting error in browser?

为什么我在浏览器中出错?

TypeError: document.body is null

类型错误:document.body 为空

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);

回答by Josh Crozier

Execute the code when the DOM loads. Wrap your logic in an event listener for DOMContentLoaded.

在 DOM 加载时执行代码。将您的逻辑包装在事件侦听器中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 事件之间的区别

回答by Sharifullah Sharif

Your document.bodyis not crated or existed yet. If you want to append child to document.bodyor do anything with document.bodyin your javascript then put your javascript cod or link of js file in the end of body tag.

你的document.body还没有装箱或存在。如果你想在你的 javascript 中附加孩子document.body或做任何事情,document.body那么把你的 javascript cod 或 js 文件的链接放在 body 标签的末尾。

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