【问题标题】:Uncaught TypeError: Cannot read properties of null (reading 'appendChild')未捕获的 TypeError:无法读取 null 的属性(正在读取“appendChild”)
【发布时间】:2021-10-21 18:11:23
【问题描述】:

我正在尝试通过 JS 在该 div 中插入一个新的 Div 和一个 img。我创建了一个类,稍后我将在其中使用一个函数,该函数应该被调用以使用该函数并插入图像。这样做时,我不断得到Uncaught TypeError: Cannot read properties of null (reading 'appendChild') HTML 和 JS 下面:

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Actividad 3</title>
<script type="text/javascript" src="actividad3.js"></script>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="style.css">


<body >
<h2>EXTRAS DISPONIBLES</h2>

    
</body>
</html>

JS

class extra {
    precio = "10€";
    url = "concha_azul.jpeg";
    constructor(precio, url) {
        this.precio = precio;
        this.url = url;
    }
    getHTML = function () {
        console.log("hello");
        var newDiv = document.createElement("div");
        newDiv.id = "x";
        var div = document.getElementById("x");
        var img = document.createElement("img");
        img.src = "concha_azul.jpeg";

        div.appendChild(img); 
    }
    
}

let miExtra = new extra();
miExtra.getHTML();

【问题讨论】:

  • 为什么会有var div = document.getElementById("x");这一行??在将其附加到 dom 之前,您无法获得该属性.. 尝试类似 newDiv.appendChild(img);..

标签: javascript html css


【解决方案1】:

当您尝试通过它的 id 抓取“newDiv”元素时,它在 HTML 文档中尚不存在。您需要先将 newDiv 元素附加到页面,然后您可以通过它的 id 检索它...

 //Create new div
 var newDiv = document.createElement("div");
 newDiv.id = "x";

 //Add div to html body
 document.body.appendChild(newDiv);

 //Get new div by it's id
 var div = document.getElementById("x");
 var img = document.createElement("img");
 img.src = "concha_azul.jpeg";
 div.appendChild(img); 

为了让事情更简单,你可以这样做......

 //Create new div
 var newDiv = document.createElement("div");
 newDiv.id = "x";

 //Add div to html body
 document.body.appendChild(newDiv);

 //Add an image element to the div
 var img = document.createElement("img");
 img.src = "concha_azul.jpeg";
 newDiv.appendChild(img); 

【讨论】:

  • 我已经尝试过了,但仍然得到 Uncaught TypeError: Cannot read properties of null (reading 'appendChild') but now for document.body.appendChild(newDiv);
  • @SamuelVanBladel “actividad3.js” 是你的额外课程的位置吗?如果是这样,页面的主体和它的元素还没有加载,所以“document.body”将返回 null。该脚本需要位于 body 标签下方。
  • 是的。我现在把它移到了 Body 标签的底部,它起作用了。在 body 标签下尝试过,但不允许。非常感谢!
猜你喜欢
  • 2022-11-21
  • 2022-11-20
  • 2022-11-24
  • 2022-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
  • 1970-01-01
相关资源
最近更新 更多