Javascript 未捕获的类型错误:无法读取 null 的属性“appendChild”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30014090/
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-08-23 04:29:42  来源:igfitidea点击:

Uncaught TypeError: Cannot read property 'appendChild' of null

javascriptajax

提问by Sparky

I'm getting the following error

我收到以下错误

Uncaught TypeError: Cannot read property 'appendChild' of null

myRequest.onreadystatechange @ script.js:20

未捕获的类型错误:无法读取 null 的属性“appendChild”

myRequest.onreadystatechange @ script.js:20

with my following code

使用我的以下代码

// index.html 
<html>
    <head>
        <title>Simple Page</title>
    </head>
    <body>
        <div id="mainContent">
            <h1>This is an AJAX Example</h1>
        </div>
        <script type="text/javascript" src="script.js"></script>
    </body>
</html>

And here is my JavaScript file

这是我的 JavaScript 文件

// script.js
// 1. Create the request

var myRequest;

// feature check!
if(window.XMLHttpRequest) { // Firefox, Safari
    myRequest = new XMLHttpRequest();
} else if (window.ActiveXObject){ // IE
    myRequest = new ActiveXObject("Microsoft.XMLHTTP");
}


// 2. Create an event handler for our request to call back 
myRequest.onreadystatechange = function() {
    console.log("We were called!");
    console.log(myRequest.readyState);
    if(myRequest.readyState === 4){
        var p = document.createElement("p");
        var t = document.createTextNode(myRequest.responseText);
        p.appendChild(t);
        document.getElementById("mainContent").appendChild(p);
    }
};

// 3. open and send it
myRequest.open("GET","simple.txt", true);

// any parameters?
myRequest.send(null);

And here is the contents of simple.txt

这里是内容 simple.txt

This is the contents of a simple text file.

这是一个简单文本文件的内容。

I put the script tag at the bottom of the html as suggested by @Tejs herebut I'm still getting this error.

按照@Tejs here 的建议将脚本标记放在 html 的底部,但我仍然收到此错误。

采纳答案by Alex McMillan

There isn't an element on your page with the id "mainContent" when your callback is being executed.

执行回调时,页面上没有 ID 为“mainContent”的元素。

In the line:

在行中:

document.getElementById("mainContent").appendChild(p);

the section document.getElementById("mainContent")is returning null

该部分document.getElementById("mainContent")正在返回null

回答by kasai-senshi

For people who have the same issue of querySelectoror getElementByIdthat returns the following error:

对于有相同问题querySelectorgetElementById返回以下错误的人:

Uncaught TypeError: Cannot read property 'appendChild' of null

but you have a class name or id in the HTML...

但是你在 HTML 中有一个类名或 id ......

If your script tag is in the head, the JavaScript is loaded before your HTML. You will need to add deferto your script like so:

如果您的脚本标记在头部,则 JavaScript 将在您的 HTML 之前加载。您需要defer像这样添加到脚本中:

<script src="script.js" defer></script>

回答by Edgar256

Nice answers here. I encountered the same problem, but I tried <script src="script.js" defer></script>but I didn't work quite well. I had all the code and links set up fine. The problem is I had put the js file link in the head of the page, so it was loaded before the DOM was loaded. There are 2 solutions to this.

不错的答案在这里。我遇到了同样的问题,但我尝试过,<script src="script.js" defer></script>但效果不佳。我的所有代码和链接都设置得很好。问题是我把js文件链接放在了页面的头部,所以它是在加载DOM之前加载的。对此有 2 种解决方案。

  1. Use
window.onload = () => {
    //write your code here
}
window.onload = () => {
    //write your code here
}
  1. Add the <script src="script.js"></script>to the bottom of the html file so that it loads last.
  1. 添加<script src="script.js"></script>到 html 文件的底部,以便它最后加载。

回答by shaheb

Use querySelector insted of getElementById();

使用 getElementById() 的 querySelector 插入;

var c = document.querySelector('#mainContent');
    c.appendChild(document.createElement('div'));

回答by VenkateshMogili

You can load your External JS files in Angular and you can load them directly instead of defining in index.html file.

你可以在 Angular 中加载你的外部 JS 文件,你可以直接加载它们而不是在 index.html 文件中定义。

component.ts:

组件.ts:

ngOnInit() {
    this.loadScripts();
}


  loadScripts() {
    const dynamicScripts = [
      //scripts to be loaded
      "assets/lib/js/hand-1.3.8.js",
      "assets/lib/js/modernizr.jr.js",
      "assets/lib/js/jquery-2.2.3.js",
      "assets/lib/js/jquery-migrate-1.4.1.js",
      "assets/js/jr.utils.js"
    ];
    for (let i = 0; i < dynamicScripts.length; i++) {
      const node = document.createElement('script');
      node.src = dynamicScripts[i];
      node.type = 'text/javascript';
      node.async = false;
      document.getElementById('scripts').appendChild(node);
    }
  }

component.html:

组件.html:

<div id="scripts">
</div>

You can also load styles similarly.

您也可以类似地加载样式。

component.ts:

组件.ts:

ngOnInit() {
    this.loadStyles();
}


  loadStyles() {
    const dynamicStyles = [
      //styles to be loaded
      "assets/lib/css/ui.css",
      "assets/lib/css/material-theme.css",
      "assets/lib/css/custom-style.css"
    ];
    for (let i = 0; i < dynamicStyles.length; i++) {
      const node = document.createElement('link');
      node.href = dynamicStyles[i];
      node.rel = 'stylesheet';
      document.getElementById('styles').appendChild(node);
    }
  }

component.html:

组件.html:

<div id="styles">
</div>